PowerShell/Scripts/check-uptime.ps1

49 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
This PowerShell script queries the computer's uptime 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
#>
try {
if ($IsLinux) {
$Uptime = (Get-Uptime)
2021-11-24 14:56:38 +01:00
} else {
$BootTime = Get-WinEvent -ProviderName eventlog | Where-Object {$_.Id -eq 6005} | Select-Object TimeCreated -First 1
2022-10-21 18:05:08 +02:00
$Uptime = New-TimeSpan -Start $BootTime.TimeCreated.Date -End (Get-Date)
2021-11-27 14:29:49 +01:00
}
2023-01-23 14:04:23 +01:00
$Reply = "✅ Up for "
$Days = $Uptime.Days
2021-11-27 14:29:49 +01:00
if ($Days -eq "1") {
2021-12-04 14:10:16 +01:00
$Reply += "1 day, "
} elseif ($Days -ne "0") {
$Reply += "$Days days, "
2021-11-27 14:29:49 +01:00
}
$Hours = $Uptime.Hours
2021-11-27 14:29:49 +01:00
if ($Hours -eq "1") {
2022-10-21 18:05:08 +02:00
$Reply += "1 hour, "
2021-12-04 14:10:16 +01:00
} elseif ($Hours -ne "0") {
2022-10-21 18:05:08 +02:00
$Reply += "$Hours hours, "
2021-11-27 14:29:49 +01:00
}
$Minutes = $Uptime.Minutes
2021-11-27 14:29:49 +01:00
if ($Minutes -eq "1") {
2022-10-21 18:05:08 +02:00
$Reply += "1 minute"
} else {
$Reply += "$Minutes minutes"
2021-11-27 14:29:49 +01:00
}
2023-01-23 14:04:23 +01:00
Write-Host $Reply
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
}