Like most things scripting, there's usually more than one way to do things. I thought I had a nice solution for getting service uptime via WMI. But alas, there is an even easier way. PowerShell has a ConvertToDateTime method which will convert a WMI time to a standard date time format.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
$p=ps winlogon
$p=get-wmiobject -query "Select * from win32_process where name='winlogon.exe'"
Looking $p.CreationDate will yield something like this:
20070217093525.074160-300
The ConvertToDatetime method can be seen here:
PS S:\PoSH > $p.ConverttoDatetime
Script : [System.Management.ManagementDateTimeConverter]::ToDateTime($args[0])
OverloadDefinitions : {System.Object ConvertToDateTime();}
MemberType : ScriptMethod
TypeNameOfValue : System.Object
Value : System.Object ConvertToDateTime();
Name : ConvertToDateTime
IsInstance : False
So to use it, all I have to do is specify the WMI Time as the argument:
PS S:\PoSH > $p.ConverttoDatetime($p.CreationDate)
Saturday, February 17, 2007 9:35:25 AM
Isn't that much easier than my convoluted string function? I can use this in its place and modify my script.
Here's the final, updated code that will work using WMI.
$computer="."
Write-Host -fore Green -back Black $computer.ToUpper()
$s=Get-WmiObject -query "Select name,processId,state from Win32_service where state='running'" -computer $computer
foreach ($item in $s) {
$query="Select handle,creationdate from win32_process where handle='"+$item.ProcessID+"'"
$p=Get-WmiObject -query $query -computer $computer
$start=$p.ConvertToDateTime($p.CreationDate)
$u=(get-date).Subtract($start)
Write-Host $item.Name `t $u.Days day $u.hours hours $u.minutes minutes and $u.seconds seconds
}
As written, it will connect to the local computer, but you can specify a remote computer name.