Answers:
发布者希望确保在尝试重新启动服务之前已将其停止。您可以在“ sc查询”的输出上使用循环,如下所示:
:stop
sc stop myservice
rem cause a ~10 second sleep before checking the service state
ping 127.0.0.1 -n 10 -w 1000 > nul
sc query myservice | find /I "STATE" | find "STOPPED"
if errorlevel 1 goto :stop
goto :start
:start
net start | find /i "My Service">nul && goto :start
sc start myservice
如果要重新启动失败的服务,则无需运行脚本。在服务MMC管理单元中,右键单击服务,选择属性,再单击“恢复”选项卡。在这里,您可以设置服务停止后要采取的措施。有很多可用的灵活性。如果您试图停止该服务,则需要一个脚本,先执行一些操作,然后启动该脚本,然后以批处理文件开头net stop "myserviceshortname"
并以结尾net start "myserviceshortname"
在vbscipt中,还有一些代码可以停止服务及其依赖者:
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery("Associators of " _
& "{Win32_Service.Name='myservice'} Where " _
& "AssocClass=Win32_DependentService " & "Role=Antecedent" )
For each objService in colServiceList
objService.StopService()
Next
Wscript.Sleep 20000
Set colServiceList = objWMIService.ExecQuery _
("Select * from Win32_Service where Name='myservice'")
For each objService in colServiceList
errReturn = objService.StopService()
Next
在这里启动服务及其所依赖的任何东西(应该很熟悉)
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
("Select * from Win32_Service where Name='Myservice'")
For each objService in colServiceList
errReturn = objService.StartService()
Next
Wscript.Sleep 20000
Set colServiceList = objWMIService.ExecQuery("Associators of " _
& "{Win32_Service.Name='myservice'} Where " _
& "AssocClass=Win32_DependentService " & "Role=Dependent" )
For each objService in colServiceList
objService.StartService()
Next