2010-05-21 82 views
4

如何停止服務並等待它停止在vbscript中?停止服務並在VBScript中等待

我有了這個迄今:

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

谷歌搜索變成了一個建議使用objService.WaitForStatus(ServiceControllerStatus.Stopped),但運行的,讓我「所需的對象:‘ServiceControllerStatus’」的錯誤。

回答

4

WaitForStatus方法不包含在WMI Win32_Service接口中。我認爲這來自.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