Controlling Uptime

by Jan 11, 2021

PowerShell 7 comes with a new cmdlet called Get-Uptime. It returns a timespan object with the time that has passed since the last reboot:

 
PS> Get-Uptime 


Days              : 9
Hours             : 23
Minutes           : 21
Seconds           : 14
Milliseconds      : 0
Ticks             : 8616740000000
TotalDays         : 9,9730787037037
TotalHours        : 239,353888888889
TotalMinutes      : 14361,2333333333
TotalSeconds      : 861674
TotalMilliseconds : 861674000 

When you submit the -Since parameter, it returns the date of the last reboot instead.

Get-Uptime isn’t available in Windows PowerShell – however it is trivial to create this command yourself. Run the following code to create your own Get-Uptime command in Windows PowerShell:

function Get-Uptime
{
    param([Switch]$Since)

    $date = (Get-CimInstance -Class Win32_OperatingSystem).LastBootUpTime
    if ($Since)
    {
        return $date
    }
    else
    {
        New-Timespan -Start $date
    }
}


Twitter This Tip! ReTweet this Tip!