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

In the automation world, you may be required to check whether the product that you wanted to test is installed and the application service is running properly.  You could use the below code to accomplish that. You could add this to a function library and associate it with QTP test. Then call the function with appropriate test parameters. For example :

strServiceStatus=sGetServiceStatus "targethostname", "ServiceName"

Below is the function:

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, "rootcimv2","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

 

One thought on “Check status of a windows service on a remote system using WMI

  1. Good one !!
    1. Add Braces for syntax error
    2. Change (strComputer, “rootcimv2″,”youradminusername” ,”youradminpassword” to
    (strComputer, “\root\cimv2″,”youradminusername” ,”youradminpassword”)

Leave a comment