Get Uptime with Get-Uptime

I’ve been using this for ages, and have now finally got around to a) blogging it, and b) updating it to use Get-CimInstance. The latter makes it particularly easy to code and thus makes the function very compact due to the way it “nicely” handles the date.

So here it is in all its glory (!):

function Get-Uptime ([string]$ComputerName = $env:COMPUTERNAME){
    (Get-Date) - (Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $ComputerName).LastBootUpTime
}

It’ll default to the local computer unless you specify -ComputerName when calling it.

Personally, I have this in my PowerShell profile, so that it’s always available for use.

As you can see, it compares the LastBootUpTime property from the Win32_OperatingSystem CIM object with the current date & time and returns the difference (as an object – so you can do stuff with it like pipe it to Select-Object etc.).

The output looks something like:

Days              : 7
Hours             : 4
Minutes           : 15
Seconds           : 54
Milliseconds      : 139
Ticks             : 6201541391309
TotalDays         : 7.17770994364468
TotalHours        : 172.265038647472
TotalMinutes      : 10335.9023188483
TotalSeconds      : 620154.1391309
TotalMilliseconds : 620154139.1309

I’ll leave it as an exercise for the reader to make it work across time zones (it really won’t take you much effort!).

Advertisements
This entry was posted in PowerShell and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s