TIPS & TRICKS

Quick PowerShell Script to Start Splunk

Got another quick PowerShell post for you. I have a copy of Splunk running locally on my Windows 8.1 workstation. I don’t always leave it running, for obvious resource reasons, therefor I end up starting it and stopping it as needed. On Windows, there’s two ways to control the Splunk services:

  • CLI splunk.exe start|stop|restart commands
  • Windows native service control methods (and there’s a half-dozen ways to do that)

So, in PowerShell, you can just do this:

Get-Service splunk* | Start-Service

The only minor problem is that I keep forgetting to elevate my PowerShell shell, so I’ll get an error message, and then I have to open a new window, and then repeat the process.  That’s no way to automate, I said to myself, so I made this quick Start-Splunk function:

Function Start-Splunk {
  try {
   Get-Service splunk* | Start-Service -ErrorAction Stop
  }
  catch [Microsoft.PowerShell.Commands.ServiceCommandException] {
    Write-Verbose "Command must be run in an elevated session, invoking new session."
    Start-Process -Verb Runas -FilePath powershell.exe { Get-Service splunk* | Start-Service -Verbose -ErrorAction Stop; Start-Sleep 5 }
  }
}

All I’m doing is catching the exception which is thrown when the call fails, and using the Start-Process cmdlet with a very useful trick to invoke PowerShell with “Run As”. That will do the right thing, and prompt you for elevation. Answer in the affirmative, and Splunk is started!

This function is also posted on gist.github.com for the cool stuff which that site provides.

Side note: you actually will have the same elevation issue if you try to start Splunk with its CLI commands. Technically, I could change the service to run as a non-system user, but that has other impact and this is just a dev environment, so there’s no point.

Hal Rottenberg
Posted by

Hal Rottenberg

Join the Discussion