views:

42

answers:

1

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 display 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'".

A: 

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".

Const MAX_ITER = 30

Set objWMIService = _
    GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")

Set colService = objWMIService.ExecQuery( _
    "Select * from Win32_Service Where Name = 'MSSQL$SQLEXPRESS'")

For Each svc In colService
    svc.StopService
Next

iter = 0
Do
    Set colService = objWMIService.ExecQuery( _
        "Select * from Win32_Service Where Name = 'MSSQL$SQLEXPRESS'")

    done = True
    For Each svc In colService
        If svc.State <> "Stopped" Then
            done = False
            WScript.Sleep 500
            Exit For
        End If
    Next

    iter = iter + 1
    If iter > MAX_ITER Then
        WScript.StdErr.WriteLine "Timeout"
        Exit Do
    End If
Loop Until done
Tmdean