Getting Uptime With PowerShell - The Fast Way

Getting uptime using WMI with PowerShell

There are already a ton of posts about getting system uptime with PowerShell, and most of them use a WMI call to Win32_OperatingSystem. Something along the lines of this:

function Uptime{
    ((Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime).ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds'")
}

Getting uptime using [System.Diagnostics.Stopwatch] with PowerShell

The issue with the above method is that WMI is sloooow. I have this in a function in my $Profile and each time I use it I notice the delay. Here’s the fix: throw WMI in the bin and replace it with [System.Diagnostics.Stopwatch].

function Uptime{
    [TimeSpan]::FromTicks([System.Diagnostics.Stopwatch]::GetTimestamp()).ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds'")
}

Comparison

Let’s compare the two, first the WMI method:

PS C:\> 1..10  | % {Measure-Command {((Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime).ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds'")}} | Measure-Object -Property TotalMilliseconds -Average

Count             : 10
Average           : 1061.91379Sum               :
Maximum           :
Minimum           :
StandardDeviation :
Property          : TotalMilliseconds

And now using [System.Diagnostics.Stopwatch]

PS C:\> 1..10  | % {Measure-Command {[TimeSpan]::FromTicks([System.Diagnostics.Stopwatch]::GetTimestamp()).ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds'")}} | Measure-Object -Property TotalMilliseconds  -Average

Count             : 10
Average           : 0.53479Sum               :
Maximum           :
Minimum           :
StandardDeviation :
Property          : TotalMilliseconds

From ~1 second average down to half a millisecond.

Annoyance fixed.


If you enjoyed this post consider sharing it on , , , or , and .