The following functions require you have Administrative privileges the to computers you are working with. These functions query the DisplayName property of the service, not the name. For instance, for the $DisplayName variable you would pass “Print Spooler” instead of “Spooler”.

I’ve used these functions to query a troublesome service that would die every once in a while. I was able to check the state and initiate a restart on the service if it were to die. The script also would send out an e-mail notifying me the services had stopped.

The following function will initiate a stop on a service and then wait 10 seconds.

Function StopService(){
     param($DisplayName, $Server)

     Write-Host("Stopping '" + $DisplayName + "' service on " + $Server + "...")

     $Filter = "DisplayName='" + $DisplayName + "'"
     $Service = Get-WmiObject -Class Win32_Service -Computer $Server -Filter $Filter

     $Null = $Service.StopService()
     Sleep 10
}

The following function will initiate a start on a service and then wait 10 seconds.

Function StartService(){
     param($DisplayName, $Server)

     Write-Host("Starting '" + $DisplayName + "' service on " + $Server + "...")    

     $Filter = "DisplayName='" + $DisplayName + "'"
     $Service = Get-WmiObject -Class Win32_Service -Computer $Server -Filter $Filter

     $Null = $Service.StartService()
     Sleep 10
}

The following function will return a System.String of a service’s current state.

Function ServiceState(){
     param($DisplayName, $Server)

     $Filter = "DisplayName='" + $DisplayName + "'"
     $Service = Get-WmiObject -Class Win32_Service -Computer $Server -Filter $Filter
     Return $Service.State
}


Gregory Strike

Husband, father, IT dude & blogger wrapped up into one good looking package.