PowerShell for Non-N00bs: System Uptime Via WMI


Getting the last time a system was rebooting is pretty easy from WMI.  From this half-decade old post, we get the two key bits: the LastBootUptTimem property of the Win32_OperatingSystem WMI class.  In PowerShell, it looks like this:


PSH> (Get-WmiObject -Query ‘SELECT LastBootUpTime FROM Win32_OperatingSystem’).LastBootUpTime
20090712112652.125000-420


The output is a little hard to read. 


PSH> $lastBootUpTimeWMIObject = (Get-WmiObject -Query ‘SELECT LastBootUpTime FROM Win32_OperatingSystem’);


PSH> $lastBootUpTimeWMIObject.ConvertToDateTime($lastBootUpTimeWMIObject.LastBootUpTime);


Sunday, July 12, 2009 11:26:52 AM 


Now, what if we want to see how long a system has been up, instead of when it was last booted up?  It turns out Get-Date can accept many different formats.


PSH> $lastBootUpDate = Get-Date ($lastBootUpTimeWMIObject.ConvertToDateTime($lastBootUpTimeWMIObject.LastBootUpTime))


PSH> ((Get-Date) – (Get-Date $lastBootUpDate)).Days


103


 

Comments (0)