Ever wonder how long a particular service has been running? With WMI you can come pretty close to getting a handle on this. We start with Win32_Service to get the current process handle. Once we have that, we can query the Win32_Process class and get the creation time for that particular process. You need to know the services display name (ie "Server") or it's service name (ie "LANMANSERVER").
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
The following script uses a WMI query to find the service based on it's display name then finds the ProcessID. We can next run another WMI query to find the process that corresponds to the ID. Once found, we get the CreationDate attribute, run it through a function to convert the WMI time format into something a little friendlier, and we're done.
This won't work for every service, especially if the service runs under the context of another process. For example, "Network Connections" runs under svchost. Even when you stop the service, the underlying process is still running so when you restart the service, you can't tell. Still for most services that run as a distinct process, these steps should work.
The script doesn't check to see if the service is running or not so if you get a result of 0, the service probably couldn't be found or isn't running.
strService="Server"
strSrv="."
strUserName=""
strPassword=""
WScript.Echo strService & " service started " &_
GetServiceUptime(strSrv,strService,strUsername,strPassword)
Function GetServiceUptime(strSrv,strService,strUsername,strPassword)
On Error Resume Next
Dim SWBemlocator,objWMI,objRef
strQuery="Select Name,ProcessID,displayname from win32_service "&_
"where displayName='" & strService & "'"
Set SWBemlocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMI = SWBemlocator.ConnectServer(strSrv,"\root\cimV2",_
strUserName,strPassword)
Set objRef=objWMI.ExecQuery(strQuery,"WQL",48)
For Each svc In objRef
iHandle=svc.ProcessID
Next
If iHandle="" Then
GetServiceUptime=0
Else
strQuery="Select Handle,CreationDate from win32_process where handle='" &_
iHandle & "'"
Set objRef=objWMI.ExecQuery(strQuery,"WQL",48)
For Each proc In objRef
dCreated=proc.CreationDate
Next
GetServiceUptime=ConvWMITime(dCreated)
End If
End Function
Function ConvWMITime(wmiTime)
On Error Resume Next
yr = left(wmiTime,4)
mo = mid(wmiTime,5,2)
dy = mid(wmiTime,7,2)
tm = mid(wmiTime,9,6)
ConvWMITime = mo&"/"&dy&"/"&yr & " " & FormatDateTime(left(tm,2) & _
":" & Mid(tm,3,2) & ":" & Right(tm,2),3)
End Function