Update check-swap-space.ps1

This commit is contained in:
Markus Fleschutz 2024-02-07 18:39:57 +01:00
parent 1498b30abf
commit 188653a71d

View File

@ -16,44 +16,46 @@
param([int]$minLevel = 10) param([int]$minLevel = 10)
function MB2String { param([int64]$Bytes) function MB2String { param([int64]$bytes)
if ($Bytes -lt 1000) { return "$($Bytes)MB" } if ($bytes -lt 1000) { return "$($bytes)MB" }
$Bytes /= 1000 $bytes /= 1000
if ($Bytes -lt 1000) { return "$($Bytes)GB" } if ($bytes -lt 1000) { return "$($bytes)GB" }
$Bytes /= 1000 $bytes /= 1000
if ($Bytes -lt 1000) { return "$($Bytes)TB" } if ($bytes -lt 1000) { return "$($bytes)TB" }
$Bytes /= 1000 $bytes /= 1000
if ($Bytes -lt 1000) { return "$($Bytes)PB" } if ($bytes -lt 1000) { return "$($bytes)PB" }
$Bytes /= 1000 $bytes /= 1000
if ($Bytes -lt 1000) { return "$($Bytes)EB" } if ($bytes -lt 1000) { return "$($bytes)EB" }
} }
try { try {
[int64]$Total = [int64]$Used = [int64]$Free = 0
if ($IsLinux) { if ($IsLinux) {
$Result = $(free --mega | grep Swap:) $Result = $(free --mega | grep Swap:)
[int64]$Total = $Result.subString(5,14) [int64]$total = $Result.subString(5,14)
[int64]$Used = $Result.substring(20,13) [int64]$used = $Result.substring(20,13)
[int64]$Free = $Result.substring(32,11) [int64]$free = $Result.substring(32,11)
} else { } else {
$Items = Get-WmiObject -class "Win32_PageFileUsage" -namespace "root\CIMV2" -computername localhost $items = Get-WmiObject -class "Win32_PageFileUsage" -namespace "root\CIMV2" -computername localhost
foreach ($Item in $Items) { [int64]$total = [int64]$used = 0
$Total += $Item.AllocatedBaseSize foreach ($item in $items) {
$Used += $Item.CurrentUsage $total += $item.AllocatedBaseSize
$Free += ($Total - $Used) $used += $item.CurrentUsage
} }
[int64]$free = ($total - $used)
} }
if ($Total -eq 0) { if ($total -eq 0) {
Write-Output "⚠️ No swap space configured" Write-Output "⚠️ No swap space configured"
} elseif ($Free -eq 0) { } elseif ($free -eq 0) {
Write-Output "⚠️ Swap space of $(MB2String $Total) is full" Write-Output "⚠️ Swap space of $(MB2String $total) is full"
} elseif ($Free -lt $minLevel) { } elseif ($free -lt $minLevel) {
Write-Output "⚠️ Swap space of $(MB2String $Total) is nearly full, only $(MB2String $Free) free" Write-Output "⚠️ Swap space of $(MB2String $total) is nearly full, only $(MB2String $free) free"
} elseif ($Used -lt 5) { } elseif ($used -lt 5) {
Write-Output "✅ Swap space unused, $(MB2String $Free) free" Write-Output "✅ Swap space unused, $(MB2String $free) free"
} else { } else {
[int]$Percent = ($Used * 100) / $Total [int]$Percent = ($used * 100) / $total
Write-Output "✅ Swap space uses $Percent% of $(MB2String $Total) · $(MB2String $Free) free" Write-Output "✅ Swap space uses $Percent% of $(MB2String $total) · $(MB2String $free) free"
} }
exit 0 # success exit 0 # success
} catch { } catch {