How to get the System uptime with PowerShell?


To get the Windows System uptime with PowerShell, we can use the CIM Instance method with class name Win32_OperatingSystem. Once you use the mentioned class there is a property called LastBootupTime which shows the date when the computer is last rebooted.

Example

Get-CimInstance -ClassName Win32_OperatingSystem | Select LastBootUpTime

Output

LastBootUpTime
--------------
9/29/2020 8:12:08 AM

If we check the datatype of the above output, it should be DateTime because of the output format.

(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.Gettype()

Output

IsPublic IsSerial Name     BaseType
-------- -------- ----     --------
True     True     DateTime System.ValueType

We need now the uptime of the system in Days-Hours-Minutes format. So we will compare the difference between the current date/time with the Bootup date/time.

$bootuptime = (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime
$CurrentDate = Get-Date
$uptime = $CurrentDate - $bootuptime
$uptime

Output

Days               : 6
Hours              : 0
Minutes            : 17
Seconds            : 38
Milliseconds       : 301
Ticks              : 5194583016830
TotalDays          : 6.01224886207176
TotalHours         : 144.293972689722
TotalMinutes       : 8657.63836138333
TotalSeconds       : 519458.301683
TotalMilliseconds  : 519458301.683

From the Output, we can say that the server is up from 6 Days and 17 minutes. We can also write the output as below.

Write-Output "Server Uptime --> Days: $($uptime.days), Hours: $($uptime.Hours), Minutes:$($uptime.Minutes)"

Output

Server Uptime --> Days: 6, Hours: 0, Minutes:17

To check the uptime on the remote computers, use -ComputerName parameter in the command. For example,

$servers = "Test1-Win2k12","Test1-Win2k16","ADDC"
$currentdate = Get-Date
foreach($server in $servers){
$Bootuptime = (Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $server).LastBootUpTime
   $uptime = $currentdate - $Bootuptime
   Write-Output "$server Uptime : $($uptime.Days) Days, $($uptime.Hours) Hours, $($uptime.Minutes) Minutes"
}

Output

Test1-Win2k12 Uptime : 5 Days, 22 Hours, 50 Minutes
Test1-Win2k16 Uptime : 5 Days, 23 Hours, 12 Minutes
ADDC Uptime : 6 Days, 2 Hours, 9 Minutes

Updated on: 01-Nov-2023

31K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements