PowerShell/scripts/check-drives.ps1

60 lines
1.9 KiB
PowerShell
Raw Normal View History

2024-10-01 15:11:03 +02:00
<#
2021-12-03 10:12:56 +01:00
.SYNOPSIS
2022-10-25 15:15:43 +02:00
Checks the drive space
2021-12-03 10:12:56 +01:00
.DESCRIPTION
2023-08-16 08:04:14 +02:00
This PowerShell script queries the free space of all drives and prints it.
.PARAMETER minLevel
2024-10-14 14:34:18 +02:00
Specifies the minimum warning level (5GB by default)
2021-12-03 10:12:56 +01:00
.EXAMPLE
2023-08-06 18:13:42 +02:00
PS> ./check-drives.ps1
2024-09-18 15:21:15 +02:00
Drive C: uses 489GB (53%) of 930GB, D: uses 3TB (87%) of 4TB, E: is empty
2021-12-03 10:12:56 +01:00
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
2022-06-09 16:30:28 +02:00
Author: Markus Fleschutz | License: CC0
2021-12-03 10:12:56 +01:00
#>
2024-10-14 14:34:18 +02:00
param([int64]$minLevel = 5GB)
2022-10-09 12:34:06 +02:00
2024-09-18 15:15:21 +02:00
function Bytes2String { param([int64]$bytes)
if ($bytes -lt 1KB) { return "$bytes bytes" }
if ($bytes -lt 1MB) { return '{0:N0}KB' -f ($bytes / 1KB) }
if ($bytes -lt 1GB) { return '{0:N0}MB' -f ($bytes / 1MB) }
if ($bytes -lt 1TB) { return '{0:N0}GB' -f ($bytes / 1GB) }
if ($bytes -lt 1PB) { return '{0:N0}TB' -f ($bytes / 1TB) }
return '{0:N0}GB' -f ($bytes / 1PB)
}
2021-12-03 10:12:56 +01:00
try {
Write-Progress "Querying drives..."
2023-08-16 08:04:14 +02:00
$drives = Get-PSDrive -PSProvider FileSystem
2024-09-14 14:05:25 +02:00
Write-Progress -completed "Done."
$status = ""
2024-09-18 15:21:15 +02:00
$reply = "Drive "
2023-08-16 08:04:14 +02:00
foreach($drive in $drives) {
$details = (Get-PSDrive $drive.Name)
if ($IsLinux) { $name = $drive.Name } else { $name = $drive.Name + ":" }
[int64]$free = $details.Free
[int64]$used = $details.Used
[int64]$total = ($used + $free)
2024-09-18 15:21:15 +02:00
if ($reply -ne "Drive ") { $reply += ", " }
2023-08-16 08:04:14 +02:00
if ($total -eq 0) {
2024-09-18 15:21:15 +02:00
$reply += "$name is empty"
2023-08-16 08:04:14 +02:00
} elseif ($free -eq 0) {
2024-09-14 14:05:25 +02:00
$status = "⚠️"
2024-09-18 15:21:15 +02:00
$reply += "$name with ($(Bytes2String $total)) is FULL"
2023-08-16 08:04:14 +02:00
} elseif ($free -lt $minLevel) {
2024-09-14 14:05:25 +02:00
$status = "⚠️"
2024-10-14 14:34:18 +02:00
$reply += "$name nearly full ($(Bytes2String $free) of $(Bytes2String $total) left)"
2021-12-03 10:12:56 +01:00
} else {
2024-09-17 16:06:01 +02:00
[int64]$percent = ($used * 100) / $total
2024-09-18 15:21:15 +02:00
$reply += "$name uses $(Bytes2String $used) ($percent%) of $(Bytes2String $total)"
2021-12-03 10:12:56 +01:00
}
}
2024-09-14 14:05:25 +02:00
Write-Host "$status $reply"
2021-12-03 10:12:56 +01:00
exit 0 # success
} catch {
2022-04-13 12:06:32 +02:00
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
2021-12-03 10:12:56 +01:00
exit 1
2023-08-05 16:20:52 +02:00
}