CheckServiceRunning.vbs

'=========================================================================
' CheckServiceRunning.vbs
' VERSION: 1.0
' AUTHOR: Brian Steinmeyer
' EMAIL: [email protected]
' WEB: https://sigkillit.com
' DATE: 1/17/2013
' COMMENTS: Pass the computer/servername to the function and the Service name
' and it will return whether the service is running.
' EXAMPLE: Check if the Print Spooler is Running
'		   strComputer = "Server"
'          strService = "Spooler"
'=========================================================================
Option Explicit
' ------ SCRIPT CONFIGURATION ------
Dim strComputer: strComputer = "Server"
Dim strService: strService = "Spooler"
' ------ END CONFIGURATION ------

Wscript.Echo CheckServiceRunning(strComputer, strService)

Private Function CheckServiceRunning(strComputer, strService)

	On Error Resume Next  ' Start Services Info Error Handling

	' Set Variables
	Dim objService, strResult: strResult = "!~ERROR~!"

    Dim objWMIService: Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Dim colServiceList: Set colServiceList = objWMIService.ExecQuery("Select * from Win32_Service WHERE Name = '" & strService & "'")
    If colServiceList.Count = 1 Then
		For Each objService in colServiceList
			If objService.State = "Running" Then
				strResult = "Running"
			Else
				'Attempt to Start Sesrvice if Not Running
				strResult = StartService(strComputer, strService)
			End If
		Next
    End If

	' Error Check
	If Err.Number <> 0 Then
		'Wscript.Echo Err.Number & vbCrLf & Err.Source & vbCrLf & Err.Description
		Err.Clear
		strResult = "!~ERROR~!"
	End If

	' Return Result
	CheckServiceRunning = "(" & strService & ")" & strResult

	On Error GoTo 0  ' End Services  Info Error Handling

End Function