PowerShell Scripts, Tips, Expert Advices, Forums, and Resources

image rotation

Welcome to PowerShell.com, the educational and community site for Windows PowerShell People. Get a quick overview.

Latest Blog Posts

08-29-2014 - PowerTip: Hide Common Code in PowerShell ISE
08-29-2014 - Event Log Providers
08-29-2014 - Friday Fun: Read Me a Story

As a Powershell.com member you will have access to:

  • Daily PowerShell tips written by Microsoft MVPs and other leading Windows PowerShell experts
  • Free Windows PowerShell advice and training provided by Microsoft MVPs and other leading Windows PowerShell experts
  • Access to leading Windows PowerShell blogs
  • A free ebook, Mastering PowerShell, written by Microsoft MVP Dr. Tobias Weltner
PowerTip of the Day

System Uptime

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)

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!

Copyright 2012 PowerShell.com. All rights reserved.