如何停止服务并等待它在vbscript中停止?
到目前为止我已经得到了这个:
For Each objService in colServiceList
If objService.DisplayName = "<my display name>" Then
objService.StopService()
End If
Next
谷歌搜索出现了使用objService.WaitForStatus( ServiceControllerStatus.Stopped )
的建议,但是运行该错误导致我出现“需要对象:'ServiceControllerStatus'”的错误。
答案 0 :(得分:4)
WMI Win32_Service接口中不包含WaitForStatus方法。我认为这是来自.NET类。没有等效的WMI方法。
您必须重新查询WMI服务对象才能获得更新状态。然后,一旦状态变为“已停止”,您就可以退出循环。
Option Explicit
Const MAX_ITER = 30, _
VERBOSE = True
Dim wmi, is_running, iter
Set wmi = GetObject("winmgmts:")
For iter = 0 To MAX_ITER
StopService "MSSQL$SQLEXPRESS", is_running
If Not is_running Then
Log "Success"
WScript.Quit 0
End If
WScript.Sleep 500
Next
Log "max iterations exceeded; timeout"
WScript.Quit 1
' stop service by name. returns false in is_running if the service is not
' currently running or was not found.
Sub StopService(svc_name, ByRef is_running)
Dim qsvc, svc
is_running = False
Set qsvc = wmi.ExecQuery( _
"SELECT * FROM Win32_Service " & _
"WHERE Name = '" & svc_name & "'")
For Each svc In qsvc
If svc.Started Then
is_running = True
If svc.State = "Running" Then svc.StopService
Log svc.Name & ": " & svc.Status
End If
Next
End Sub
Sub Log(txt)
If VERBOSE Then WScript.StdErr.WriteLine txt
End Sub