Get-SystemUptime and Working with the WMI Date Format

PowerShell Team

I just got a quick ping from someone at work for an uptime script.  I checked in WMI with by using Search-WmiHelp to find a wmi class that had an uptime property (Win32_OperatingSystem has LastBootUpTime).  While I had found the uptime property I needed, I was left with another pretty common problem that people hit (in VBScript and in PowerShell) about dealing with WMI times.  WMI has a couple of date time formats, and moving in and out of these formats often involves messy parsing code.  Luckily, the WMI team was nice enough to make sure that the .NET classes you use to work with WMI can convert dates, times, and timespans.  I guessed there might be one such class, and I used a quick Get-Type function to get all loaded types, and then piped the results into Where-Object to find a type where the fullname was like *Management*DateTime*.  This led me to System.Management.ManagementDateTimeConverter.  Not only does this class have the missing chunk to turn a WMI Time into a DateTime, but it also has the methods to turn it back and it has similar methods for timespans.

With coding and with life, it’s not the destination but the journey that matters most.  I was able to learn some about how to work with WMI Dates in .NET and make a better uptime script.  I was able to do most of this building upon the richness of PowerShell and I was able to work through the sea of types with scripts I’d written before.  I hope the journey was educational.

function Get-SystemUptime
{
    $operatingSystem = Get-WmiObject Win32_OperatingSystem
    [Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)
}

Hope this Helps,

James Brundage [MSFT]

0 comments

Discussion is closed.

Feedback usabilla icon