7

Is there anyway to check the status of service using vbscript ? I would like to have a function for each possible service state : LINK Any help would be great. I did write a function for checking if service is stopped :

Public Function IsServiceStop(ByVal serviceName)
    On Error Resume Next
    Dim objServices, service
    Set oWmiService = GetObject("winmgmts:\\.\root\cimv2")
    Set objServices = oWmiService.ExecQuery("Select * from Win32_Service where Name='" & serviceName & "'")
    For Each service In objServices
        IsServiceStop = (service.Started = False)
        Exit Function
    Next
    IsServiceStop = True
    On Error Goto 0
End Function
essential
  • 648
  • 1
  • 7
  • 19
Anh Nguyen
  • 313
  • 5
  • 11
  • 22
  • WMI itself is a service. It may not be available. `Windows Management Instrumentation` – Azevedo Sep 18 '18 at 17:44
  • @Azevedo While it's true that WMI service may not be running, if that's the case, so much stuff doesn't work that it's not worth worrying about in my experience. – Walt Sep 04 '20 at 18:20

3 Answers3

5

When in doubt, read the documentation. All you need to do is check the State property of the service object:

serviceName = "..."

Set wmi = GetObject("winmgmts://./root/cimv2")
state = wmi.Get("Win32_Service.Name='" & serviceName & "'").State
WScript.Echo state
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
3
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")

Set colListOfServices = objWMIService.ExecQuery ("Select * from Win32_Service Where Name ='" & strServiceName & "'")

For Each objService in colListOfServices

   status = objService.State

Next

Reporter.ReportEvent micPass, "startService", "Service status " & status
bummi
  • 27,123
  • 14
  • 62
  • 101
arvind123
  • 71
  • 2
2
' Michael Maher 
' 3/10/07 
' Checks if services exists and is running 

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

Set colRunningServices = objWMIService.ExecQuery("Select * from Win32_Service Where Name='Messenger'")  
nItems = colRunningServices.Count  

' If the collection count is greater than zero the service will exist. 

If nItems > 0  Then 

For Each objItem in colRunningServices 

If objItem.State = "Stopped" Then 
Wscript.Echo objItem.DisplayName & " Installed/Stopped" 
ElseIf objItem.State = "Started" Then 
Wscript.Echo objItem.DisplayName & " Installed/Running" 
End If 
Next 

Else 
Wscript.Echo "Service Not Installed" 
End If 

Here is the source

Klavyen
  • 43
  • 1
  • 7