By William Jeffrey Rankin, Sun Nov 27 2022
A basic version of the Unix uptime command, implemented in PowerShell. Reports uptime only (not user count or load averages). Testing using PowerShell 7.3 and 5.1 on Windows 10.
jeffr@CALLISTO: D:\Documents\Uptime $ .\uptime.ps1
CALLISTO: 11/27/2022 16:22:20 up 07:12:48
jeffr@IO: C:\Users\jeffr\Documents\Uptime $ .\uptime.ps1
IO: 11/27/2022 16:24:55 up 2 days, 08:32:54
# uptime - Basic PowerShell implementation of the Unix uptime command
# $Author: jeffr $
# $Date: 2022-11-30 17:04:08 -0500 (Wed, 30 Nov 2022) $
# $Revision: 4 $
$c_time = Get-Date
$b_time = Get-CimInstance -ClassName win32_operatingsystem | Select-Object lastbootuptime
$d_time = New-TimeSpan -Start $b_time.lastbootuptime -End $c_time
$a_d_time = ($d_time.ToString()).Split(':')
# Days and hours
if ($a_d_time[0].Contains('.')) {
$a_days = $a_d_time[0].Split('.')
# Day or days?
if ($a_days[0] -eq 1) {
$d_str = 'day'
} else {
$d_str = 'days'
}
$days = "$($a_days[0]) $($d_str), "
$hours = $a_days[1]
} else {
$days = ''
$hours = $a_d_time[0]
}
# Minutes
$minutes = $a_d_time[1]
# Seconds
$a_seconds = ($a_d_time[$a_d_time.Length - 1]).Split('.')
# Output the result
Write-Host "$($env:computername): $($c_time) up $($days)$($hours):$($minutes):$($a_seconds[0])"