' http://techtasks.com/code/viewbookcode/376
' ishi na saite po slovam : Robust service restart

' From the book "Windows XP Cookbook"
' ISBN: 0596007256

' This code restarts a service by first stopping all
' dependent services before stopping the target service.
' Then the target service is started and all dependent
' services are started.

Option Explicit

' ------ SCRIPT CONFIGURATION ------
Dim strComputer : strComputer = "." ' e.g. fs-rtp01
Dim strSvcName : strSvcName = "spooler" ' e.g. dnscache
' ------ END CONFIGURATION ---------
Dim objWMI : set objWMI = GetObject("winmgmts:\\" & strComputer & _
"\root\cimv2")
Dim objService: set objService = objWMI.Get("Win32_Service.Name='" & _ strSvcName & "'")

WScript.Echo "Restarting " & objService.Name & "..."
RecursiveServiceStop objService
RecursiveServiceStart objService
WScript.Echo "Successfully restarted service"

Function RecursiveServiceStop ( objSvc )

Dim colServices : set colServices = objWMI.ExecQuery("Associators of " _
& "{Win32_Service.Name='" & objSvc.Name & "'} Where " _
& "AssocClass=Win32_DependentService Role=Antecedent" )
Dim objS
for each objS in colServices
RecursiveServiceStop objS
next

Dim intRC : intRC = objSvc.StopService
if intRC > 0 then
WScript.Echo " Error stopping service: " & objSvc.Name
WScript.Quit
else
WScript.Echo " Successfully stopped service: " & objSvc.Name
end if
End Function

Function RecursiveServiceStart ( objSvc )

Dim intRC : intRC = objSvc.StartService
if intRC > 0 then
WScript.Echo " Error starting service: " & objSvc.Name
WScript.Quit
else
WScript.Echo " Successfully started service: " & objSvc.Name
end if

Dim colServices : set colServices = objWMI.ExecQuery("Associators of " _
& "{Win32_Service.Name='" & objSvc.Name & "'} Where " _
& "AssocClass=Win32_DependentService Role=Antecedent" )
Dim objS
for each objS in colServices
RecursiveServiceStart objS
next

End Function