Intro

PowerShell for the longest time lacked a proper way to check uptime on the machine you were working on. This was something I was always going to the GUI for, up until recently when I discovered a simple function that I can use to gather the uptime on a Windows machine, regardless of it’s PowerShell version.

The Code

Pre-PowerShell 7

(Get-Date) - (gcim Win32_OperatingSystem).LastBootUpTime

Days              : 0
Hours             : 1
Minutes           : 9
Seconds           : 41
Milliseconds      : 536
Ticks             : 41815368642
TotalDays         : 0.0483974174097222
TotalHours        : 1.16153801783333
TotalMinutes      : 69.69228107
TotalSeconds      : 4181.5368642
TotalMilliseconds : 4181536.8642

Post-PowerShell 7

Get-Uptime

Days              : 0
Hours             : 1
Minutes           : 7
Seconds           : 19
Milliseconds      : 0
Ticks             : 40390000000
TotalDays         : 0.0467476851851852
TotalHours        : 1.12194444444444
TotalMinutes      : 67.3166666666667
TotalSeconds      : 4039
TotalMilliseconds : 4039000

You see that Post-PowerShell 7 goodness? Where has that been? Anyway, it’s here now. For machines running Pre-PowerShell 7, I have a function in my $PROFILE that I load in so that I have the convenient access to Get-Uptime no matter where I am.

Get-Uptime Function

function Get-Uptime {
  (Get-Date) - (gcim Win32_OperatingSystem).LastBootUpTime
}

For the Purists

Admitedly I’m far from a purist, but I do prefer Unix-like commands instead of PowerShell’s verbose way of describing things, so I do have an alias set for this in my $PROFILE as well.

Set-Alias -Name uptime -Value Get-Uptime

This saves me from remembering one more verbose command in PowerShell!

Conclusion

That’s all for now. I hope this snippet helps you as much as it helped me! I remote into Windows machines all the time and we all know that a long uptime on a Windows machine can only mean one thing… problems.

Until next time!