PowerShell/docs/check-drives.md
2024-01-25 13:37:12 +01:00

3.0 KiB

Script: check-drives.ps1

This PowerShell script queries the free space of all drives and prints it.

Parameters

PS> ./check-drives.ps1 [[-minLevel] <Int64>] [<CommonParameters>]

-minLevel <Int64>
    Specifies the minimum warning level (10 GB by default)
    
    Required?                    false
    Position?                    1
    Default value                10
    Accept pipeline input?       false
    Accept wildcard characters?  false

[<CommonParameters>]
    This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, 
    WarningVariable, OutBuffer, PipelineVariable, and OutVariable.

Example

PS> ./check-drives.ps1
 Drive C: uses 49%, 512GB free of 1TB
 Drive D: uses 84%, 641GB free of 4TB

Notes

Author: Markus Fleschutz | License: CC0

https://github.com/fleschutz/PowerShell

Script Content

<#
.SYNOPSIS
	Checks the drive space
.DESCRIPTION
	This PowerShell script queries the free space of all drives and prints it.
.PARAMETER minLevel
	Specifies the minimum warning level (10 GB by default)
.EXAMPLE
	PS> ./check-drives.ps1
	✅ Drive C: uses 49%, 512GB free of 1TB
	✅ Drive D: uses 84%, 641GB free of 4TB
.LINK
	https://github.com/fleschutz/PowerShell
.NOTES
	Author: Markus Fleschutz | License: CC0
#>

param([int64]$minLevel = 10) # 10 GB minimum

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"
}

try {
	Write-Progress "Querying drives..."
	$drives = Get-PSDrive -PSProvider FileSystem
	$minLevel *= 1000 * 1000 * 1000
	Write-Progress -completed " "
	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)

		if ($total -eq 0) {
			Write-Host "✅ Drive $name is empty"
		} elseif ($free -eq 0) {
			Write-Host "⚠️ Drive $name with $(Bytes2String $total) is full"
		} elseif ($free -lt $minLevel) {
			Write-Host "⚠️ Drive $name with $(Bytes2String $total) is nearly full, $(Bytes2String $free) free"
		} else {
			[int]$percent = ($used * 100) / $total
			Write-Host "✅ Drive $name uses $percent%, $(Bytes2String $free) free of $(Bytes2String $total)"
		}
	}
	exit 0 # success
} catch {
	"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
	exit 1
}

(generated by convert-ps2md.ps1 using the comment-based help of check-drives.ps1 as of 01/25/2024 13:36:49)