PowerShell/scripts/check-drives.ps1

57 lines
1.8 KiB
PowerShell
Raw Normal View History

2023-10-31 12:05:32 +01: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-02-08 12:09:35 +01:00
Specifies the minimum warning level (10GB by default)
2021-12-03 10:12:56 +01:00
.EXAMPLE
2023-08-06 18:13:42 +02:00
PS> ./check-drives.ps1
Drive C: has 512GB free (49% of 1TB used)
Drive D: has 641GB free (84% of 4TB used)
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-21 23:20:29 +02:00
param([int64]$minLevel = 10) # 10 GB minimum
2022-10-09 12:34:06 +02:00
2024-02-08 12:09:35 +01:00
function Bytes2String { param([int64]$number)
if ($number -lt 1KB) { return "$number bytes" }
if ($number -lt 1MB) { return '{0:N0}KB' -f ($number / 1KB) }
if ($number -lt 1GB) { return '{0:N0}MB' -f ($number / 1MB) }
if ($number -lt 1TB) { return '{0:N0}GB' -f ($number / 1GB) }
if ($number -lt 1PB) { return '{0:N0}TB' -f ($number / 1TB) }
return '{0:N0}GB' -f ($number / 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-02-08 12:09:35 +01:00
$minLevel *= 1GB
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 full"
2023-08-16 08:04:14 +02:00
} 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 {
2024-03-16 11:36:02 +01:00
[int64]$percent = ($used * 100) / $total
Write-Host "✅ Drive $name has $(Bytes2String $free) free ($percent% of $(Bytes2String $total) used)"
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
}