How To Get the System Uptime

There are many ways to obtain the system uptime from Windows GUI.

Just to list a couple:

  • Task Manager, Performance, Up Time. 
  • From the command prompt using the command prompt systeminfo ( system boot time).

But why don’t use Powershell or BaSH?

POWERSHELL

PS C:\Users\system.team> Get-CimInstance -ClassName win32_operatingsystem | Select-Object -exp LastBootUpTime
7/07/2017 12:07:06 PM

If you are using PowerShell version later than 5.1

#Requires -Version 5.1
Get-ComputerInfo | select-object oslastbootuptime

BASH

[boss@scriptingbox ~]# uptime
[boss@scriptingbox ~]# uptime
19:02:15 up 10:47, 2 users, load average: 0.16, 0.03, 0.01

The result looks similar, but what if we want to get from PowerShell just the uptime instead the last boot up time?

The New-TimeSpan cmdlet will help us to achieve what we really want:

PS C:\Users\system.team> $boot = (Get-CimInstance -ClassName win32_operatingsystem | Select-Object LastBootUpTime ).lastbootuptime
PS C:\Users\system.team> $now = Get-Date
PS C:\Users\system.team> New-TimeSpan -start $boot -end $now



Days : 5
Hours : 3
Minutes : 11
Seconds : 33
Milliseconds : 572
Ticks : 4434935728379
TotalDays : 5.13302746340162
TotalHours : 123.192659121639
TotalMinutes : 7391.55954729833
TotalSeconds : 443493.5728379
TotalMilliseconds : 443493572.8379

Or in a one-liner

New-TimeSpan -start $((Get-CimInstance -ClassName win32_operatingsystem ).lastbootuptime) -end $(Get-Date)

2 Replies to “How To Get the System Uptime”

  1. I think that you meant to omit line 1. Line 2 $now should be $today. You can do, uptime, with a one liner, in PowerShell, as well without the variables. New-TimeSpan -Start (Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime -End (Get-Date)

    1. Hi Micheal,
      Thanks for your comment and for adding another way to get with a oneliner the uptime and for finding an error.
      Regards

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.