Check status of a windows service on a remote system using WMI

Send Us a Sign! (Contact Us!)
--> (Word) --> (PDF) --> (Epub) --> (Text)
--> (XML) --> (OpenOffice) --> (XPS)

In the automation world, you may be required to check whether the product that you wanted to [gs test] is installed and the application [gs service] is running properly. You could use the below code to accomplish that. Then call the function with appropriate test parameters.

For example :

strServiceStatus=sGetServiceStatus "targethostname", "ServiceName"

Below is the function (be sure to specify the password and the username of an administrative’s user):

Function sGetServiceStatus(ByVal strComputer, ByVal strServiceName)
if(strComputer = "") then
sGetServiceStatus = ""
Exit function
end if
wbemImpersonationLevelImpersonate = 3
wbemAuthenticationLevelPktPrivacy = 6
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMIService = objLocator.ConnectServer _
(strComputer, "/root/CIMV2","youradminusername" ,"youradminpassword"
objWMIService.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate
objWMIService.Security_.AuthenticationLevel = wbemAuthenticationLevelPktPrivacy
Set colListOfServices = objWMIService.ExecQuery _
("Select * from Win32_Service Where DisplayName ='"& strServiceName & "'")
if(colListOfServices.Count=0) then
sGetServiceStatus = ""
Exit function
end if
For Each objItem in colListOfServices
If objItem.DisplayName = strServiceName and objItem.State = "Running" Then
sGetServiceStatus = objItem.State
Exit Function
else
sGetServiceStatus = objItem.State
Exit function
End If
Next
sGetServiceStatus = ""
End Function
SOURCE

LINK (haripotter.wordpress.com)

LANGUAGE
ENGLISH