Wednesday, January 27, 2010

Restart a service from the Command line

Taken from Robbie Allen webpage : Robust_restart.vbs
(the problem is that it doesn't work because of an underscore "_" before the strSvcName variable. Remove it just as it is listed below.
Of course you can specify the strComputer(server name) and strSvcName (service shortname, for e.g. Audiosrv and not "windows audio" cause it won't work in the other way).

Restart.vbs
----------------------------------------------------------------------------------------------

strService = "spooler"
strComputer = "."

WScript.Echo "Restarting " & strService & "..."

' Stop dependent services
Set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objServiceList = objWMI.ExecQuery("Associators of " _
& "{Win32_Service.Name='" & strService & "'} Where " _
& "AssocClass=Win32_DependentService " & "Role=Antecedent" )
For Each objService In objServiceList
WScript.Echo " Stopping " & objService.Name
objService.StopService()
Next
WScript.Sleep 10000 ' Pause to allow services to stop
' Stop target service
Set objService = objWMI.Get("Win32_Service.Name='" & strService & "'")
WScript.Echo " Stopping " & objService.Name
objService.StopService()
WScript.Sleep 10000 ' Pause to allow service to stop

' Start target service
Set objService = objWMI.Get("Win32_Service.Name='" & strService & "'")
WScript.Echo " Starting " & objService.Name
objService.StartService()
WScript.Sleep 10000 ' Pause to allow service to start

' Start dependent services
Set objServiceList = objWMI.ExecQuery("Associators of " _
& "{Win32_Service.Name='" & strService & "'} Where " _
& "AssocClass=Win32_DependentService " & "Role=Antecedent" )
For Each objService In objServiceList
WScript.Echo " Starting " & objService.Name
objService.StartService()
Next
WScript.Echo "The script has completed successfully."
----------------------------------------------------------------------------------------------

To be run from a command line/script
Just type : cscript restart.vbs


What's the difference with this and doing a net stop service /y & net start service?
The difference is that if you have dependant services they will not start.
While using this script, it will start any dependant service as well as the requested service but it's not perfect. It will fail to tell the truth if a dependant service doesn't start. I would use sc.exe to query the service state after the restart script finished.

0 comments:

Post a Comment