PowerShell/scripts/check-uptime.ps1

43 lines
1.1 KiB
PowerShell
Raw Normal View History

2023-10-31 12:12:58 +01:00
<#
2021-11-24 14:56:38 +01:00
.SYNOPSIS
Checks the uptime
2021-11-24 14:56:38 +01:00
.DESCRIPTION
2023-10-11 08:10:02 +02:00
This PowerShell script queries the computer's uptime (time between now and last boot up time) and prints it.
2021-11-24 14:56:38 +01:00
.EXAMPLE
2023-08-06 21:35:36 +02:00
PS> ./check-uptime.ps1
2024-02-07 13:38:38 +01:00
OfficePC is up for 13 days since 1/25/2024
2021-11-24 14:56:38 +01:00
.LINK
https://github.com/fleschutz/PowerShell
2022-01-29 12:47:46 +01:00
.NOTES
2022-09-06 21:42:04 +02:00
Author: Markus Fleschutz | License: CC0
2021-11-24 14:56:38 +01:00
#>
2024-02-21 16:32:16 +01:00
function TimeSpanAsString([TimeSpan]$uptime)
2023-10-17 21:54:47 +02:00
{
[int]$days = $uptime.Days
[int]$hours = $days * 24 + $uptime.Hours
if ($days -gt 2) {
return "$days days"
} elseif ($hours -gt 1) {
return "$hours hours"
} else {
return "$($uptime.Minutes)min"
}
}
2021-11-24 14:56:38 +01:00
try {
2024-02-21 16:32:16 +01:00
[system.threading.thread]::currentthread.currentculture = [system.globalization.cultureinfo]"en-US"
2021-11-24 14:56:38 +01:00
if ($IsLinux) {
2024-02-21 16:32:16 +01:00
$lastBootTime = (Get-Uptime -since)
2023-10-11 08:10:02 +02:00
$uptime = (Get-Uptime)
2021-11-24 14:56:38 +01:00
} else {
2023-10-11 08:10:02 +02:00
$lastBootTime = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
$uptime = New-TimeSpan -Start $lastBootTime -End (Get-Date)
2021-11-27 14:29:49 +01:00
}
2024-02-21 16:32:16 +01:00
Write-Host "$(hostname) is up for $(TimeSpanAsString $uptime) since $($lastBootTime.ToShortDateString())"
2021-11-24 14:56:38 +01:00
exit 0 # success
} catch {
2022-04-13 12:06:32 +02:00
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
2021-11-24 14:56:38 +01:00
exit 1
2023-08-06 21:35:36 +02:00
}