停止服务并在VBScript中等待

时间:2010-05-21 18:24:50

标签: vbscript service

如何停止服务并等待它在vbscript中停止?

到目前为止我已经得到了这个:

For Each objService in colServiceList
    If objService.DisplayName = "<my display name>" Then
        objService.StopService()
    End If
Next

谷歌搜索出现了使用objService.WaitForStatus( ServiceControllerStatus.Stopped )的建议,但是运行该错误导致我出现“需要对象:'ServiceControllerStatus'”的错误。

1 个答案:

答案 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