How can I stop a service and wait for it to finish stopping in vbscript?
I've got this so far:
For Each objService in colServiceList
If objService.DisplayName = "<my dis开发者_如何转开发play name>" Then
objService.StopService()
End If
Next
Googling turned up a suggestion of using objService.WaitForStatus( ServiceControllerStatus.Stopped )
, but running that gives me an error of "Object required: 'ServiceControllerStatus'".
The WaitForStatus method isn't included in the WMI Win32_Service interface. I think that's from a .NET class. There's no equivalent WMI method.
You have to requery the WMI service object in order to get an updated status. Then you can exit a loop once the status changes to "Stopped".
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
精彩评论