PowerShell/Scripts/check-drives.ps1

61 lines
1.8 KiB
PowerShell
Raw Normal View History

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
Specifies the minimum warning level (10 GB by default)
2021-12-03 10:12:56 +01:00
.EXAMPLE
2023-08-06 18:13:42 +02:00
PS> ./check-drives.ps1
2023-08-16 08:04:14 +02:00
Drive C: at 49% of 1TB, 512GB free
Drive D: at 84% of 4TB, 641GB free
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
#>
2023-08-16 08:04:14 +02:00
param([int]$minLevel = 10) # 10 GB minimum
2022-10-09 12:34:06 +02:00
2023-08-16 08:04:14 +02:00
function Bytes2String { param([int64]$bytes)
if ($bytes -lt 1000) { return "$bytes bytes" }
$bytes /= 1000
if ($bytes -lt 1000) { return "$($bytes)KB" }
$bytes /= 1000
if ($bytes -lt 1000) { return "$($bytes)MB" }
$bytes /= 1000
if ($bytes -lt 1000) { return "$($bytes)GB" }
$bytes /= 1000
if ($bytes -lt 1000) { return "$($bytes)TB" }
$bytes /= 1000
return "$($bytes)PB"
}
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
2023-08-05 15:58:50 +02:00
Write-Progress -completed "."
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)
2021-12-03 10:12:56 +01:00
2023-08-16 08:04:14 +02:00
if ($total -eq 0) {
Write-Host "✅ Drive $name is empty"
} elseif ($free -eq 0) {
Write-Host "⚠️ Drive $name with $(Bytes2String $total) is 100% full"
} elseif ($free -lt $minLevel) {
Write-Host "⚠️ Drive $name with $(Bytes2String $total) is nearly full, $(Bytes2String $free) free"
2021-12-03 10:12:56 +01:00
} else {
2023-08-16 08:04:14 +02:00
[int]$percent = ($used * 100) / $total
Write-Host "✅ Drive $name at $percent% of $(Bytes2String $total), $(Bytes2String $free) free"
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
}