Recipes by topic

Last boot time and uptime

Win32_OperatingSystem exposes LastBootUpTime (date of the last boot) and LocalDateTime (current time on the machine). The difference between the two is the uptime.

$operatingSystem = Get-CimInstance -ClassName Win32_OperatingSystem
$uptime = $operatingSystem.LocalDateTime - $operatingSystem.LastBootUpTime

[PSCustomObject]@{
    ComputerName = $operatingSystem.CSName
    LastBoot     = $operatingSystem.LastBootUpTime
    Uptime       = '{0}d {1:00}h {2:00}m' -f $uptime.Days, $uptime.Hours, $uptime.Minutes
}

Get-CimInstance already returns [datetime] values, so no conversion is needed. The calculation starts from LocalDateTime rather than Get-Date, so it stays correct when the clock of the queried machine differs from yours. With Windows fast startup, a shutdown followed by a power-on does not reset LastBootUpTime: only a restart does.

Variant: remote

One session per server; the machines that were started longest ago come first.

$cimSession = New-CimSession -ComputerName 'SERVER01', 'SERVER02'
try {
    $cimParameters = @{
        CimSession = $cimSession
        ClassName  = 'Win32_OperatingSystem'
    }
    Get-CimInstance @cimParameters |
        Select-Object -Property @(
            'PSComputerName'
            'LastBootUpTime'
            @{ Name = 'Uptime'; Expression = { $_.LocalDateTime - $_.LastBootUpTime } }
        ) |
        Sort-Object -Property LastBootUpTime
} finally {
    Remove-CimSession -CimSession $cimSession
}

Classes used

← All recipes