Recently, in my new role of Splunk Admin, I took over maintaining our list of installed Universal Forwarders installed on Windows servers. In order to make my job and life a little bit easier, I dove into the world of PowerShell scripting. After many hours I came up with a simple script that would allow me to call a function called “UFCheck”, give it a server name, and the script would do the rest.
- It sets the Error Action to Silently Continue, for sanity reasons.
- It checks for the existence of the SplunkForwarder service in Windows and determines its state.
- If it is not running, it starts it and then returns the new status.
- If the SplunkForwarder service is running, it tells you it is already running.
- If the SplunkForwarder service is not present, it tells you it is not present on the system.
- After each Switch taken, it returns the Error Action to its default state.
$ErrorActionPreference = "SilentlyContinue" # Comment this out if you like red text # Let us make this a function to make life easier # Now, just type UFCheck -ComputerName "name_of_computer" Function UFCheck { param( [Parameter(Position=0,Mandatory=$true)][string]$ComputerName ) #Requiring the name of the computer as the "-ComputerName" parameter $Service = Get-Service -ComputerName $ComputerName SplunkForwarder # Checking for the existence of the SplunkForwarder service and feeding it $Service # Now it is time to see our results of $Service and choose TRUE or FALSE Switch ($Service.Name -eq "SplunkForwarder") { TRUE { If ($Service.Status -ne "Running") { $Service.Start() #Starting the SplunkForwarder service and printing some pretty text to the console Write-Host "Starting the SplunkForwarder service..." "--------------------------" Start-Sleep -Seconds 20 $Result = If (($_|get-service).status -eq "Running") {"started"} else {"NOT started"} # Check to see if it is running again after the start command from earlier and storing as $Result Write-Host "The SplunkForwarder service was $Result successfully." # Showing the user our $Result from earlier $ErrorActionPreference = "Continue" # Putting things back to how they were } ElseIf ($Service.Status -eq "Running") { Write-Host "The SplunkForwarder service is already running." # Telling them it was already running, if it was already running $ErrorActionPreference = "Continue" # Putting things back to how they were } } FALSE { Write-Host "The SplunkForwarder service was not found." # Oh, no! The service is nowhere to be found. You know what to do next! $ErrorActionPreference = "Continue" # Putting things back to how they were } } }
That’s it. It is simple, must be ran each time in order to call the function, because it does not store itself. I think that will be next.
If you have any recommendations on how to make the script better, please leave a comment below!