PowerShell/Scripts/check-uptime.ps1

43 lines
1.1 KiB
PowerShell
Raw Normal View History

2021-11-24 14:59:01 +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
Up for 2 days, 20 hours, 10 minutes
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
#>
2023-10-17 21:54:47 +02:00
function TimeSpan2String([TimeSpan]$uptime)
{
[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 {
if ($IsLinux) {
2023-10-11 08:10:02 +02:00
$uptime = (Get-Uptime)
2023-10-17 21:54:47 +02:00
Write-Host "✅ Up for $(TimeSpan2String $uptime)"
2021-11-24 14:56:38 +01:00
} else {
2023-10-17 21:54:47 +02:00
[system.threading.thread]::currentthread.currentculture = [system.globalization.cultureinfo]"en-US"
2023-10-11 08:10:02 +02:00
$lastBootTime = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
$uptime = New-TimeSpan -Start $lastBootTime -End (Get-Date)
2023-10-17 21:54:47 +02:00
Write-Host "✅ Up for $(TimeSpan2String $uptime) since $($lastBootTime.ToShortDateString())"
2021-11-27 14:29:49 +01:00
}
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
}