System Uptime

by Aug 29, 2014

All PowerShell Versions

Windows starts a high definition counter each time it boots, and this counter will return the milliseconds the system runs:

$millisecondsUptime = [Environment]::TickCount
"I am up for $millisecondsUptime milliseconds!"

Since you will hardly be interested in the milliseconds, use New-Timespan to turn the milliseconds (or any other time interval for that matter) into a meaningful unit:

$millisecondsUptime = [Environment]::TickCount
"I am up for $millisecondsUptime milliseconds!"

$timespan = New-TimeSpan -Seconds ($millisecondsUptime/1000)
$timespan

So now, you can use the timespan object in $timespan to report the uptime in any unit you want:

$millisecondsUptime = [Environment]::TickCount
"I am up for $millisecondsUptime milliseconds!"

$timespan = New-TimeSpan -Seconds ($millisecondsUptime/1000)
$hours = $timespan.TotalHours

"System is up for {0:n0} hours now." -f $hours

As a special treat, New-Timespan cannot take milliseconds directly, so the script had to divide the milliseconds by 1000, introducing a small inaccuracy.

To turn milliseconds in a timespan object without truncating anything, try this:

$timespan = [Timespan]::FromMilliseconds($millisecondsUptime)

It won't make a difference in this example, but can be useful elsewhere. For example, you also have a FromTicks() method available that can turn ticks (the smallest unit of time intervals on Windows systems) into intervals.

Twitter This Tip! ReTweet this Tip!