Check State of Service, Start if Stopped

 

Interestingly, this seemingly simple task took me a bit to track down, and get put together. You’d think this would be a common task with lots of posts about it, but most of what I found was confined to starting and stopping the service, and few had the whole “check state” part included. I found several posts, but none of them worked for me. Finally, I found this post by Ralf Schäftlein that did the trick. In Ralf’s post, he is checking all VMWare services. My goal was to check and start SQL services of a particular SQL instance on a server, so I had to tweak his script ever so slightly to make it work. Here it is:

#This script uses the $SQLInstance variable to check if a particular SQL Instance’s services are running and start them if stopped.

$SQLInstance = “INSTANCENAME”

foreach ($svc in Get-Service)

{

if(($svc.displayname.Contains(“$SQLInstance”)) -AND ($svc.Status -eq “Stopped”))

{ echo $svc.DisplayName

Start-Service $svc.name

}

}

Save this as sqlservicecheck.ps1 and run it and you should be good to go. Quick note, the instance name search using .Contains is CASE SENSATIVE! That one added about 10 minutes to testing.

 

Advertisements