Start a Service via ADSI
I recently ran into the problem of WMI being stopped on workstations. As such I needed to find an easy way to start the service on the box locally without using WMI. The code snippet below uses WSH and ADSI to start WMI. If it fails it attempts to run sc.exe.
Interesting. I am also writing another entry about 7 other methods.
Here:
' ========================================================
' Method: StartWMIbyADSI
' ========================================================
Sub StartWMIbyADSI()
On Error Resume Next
Dim WSHShell: Set WSHShell = CreateObject("WScript.Shell")
If err <> 0 Then Wscript.Echo “ Failed to create Wscript.Shell object”
' define a constant for stopped services
' define ADSI status constants
Const ADS_SERVICE_STOPPED = 1
Const ADS_SERVICE_START_PENDING = 2
Const ADS_SERVICE_STOP_PENDING = 3
Const ADS_SERVICE_RUNNING = 4
Const ADS_SERVICE_CONTINUE_PENDING = 5
Const ADS_SERVICE_PAUSE_PENDING = 6
Const ADS_SERVICE_PAUSED = 7
Const ADS_SERVICE_ERROR = 8
' get an ADSI object for a computer
Set objComputer = GetObject("WinNT://" & COMPUTER & ",computer")
' get an object for a service
Set objService = objComputer.GetObject("Service","winmgmt")
' check to see if the service is stopped
If (objService.Status = ADS_SERVICE_STOPPED) Then
' if the service is stopped, then start it
objService.Start
If Err.number<>0 Then 'Exit sub
'Start Failed
'Try starting by SC.exe
SCEXELocation = %systemroot% & “\system32”
wshshell.run SCEXELocation & "\sc.exe config winmgmt start= auto",0,1
wshshell.run SCEXELocation & "\sc.exe start winmgmt",0,1
Wscript.Quit
End If
While objService.Status <> ADS_SERVICE_RUNNING: Wend
End If
If Err <> 0 Then Wscript.Echo "ERROR StartWMIbyADSI"
On Error GoTo 0
End Sub
Reference: http://support.microsoft.com/kb/247557
Reference: http://msdn.microsoft.com/en-us/library/aa746326.aspx