PowerShell/Docs/check-drives.md
2022-11-18 17:02:20 +01:00

2.5 KiB

The check-drives.ps1 PowerShell Script

This PowerShell script checks all drives for free space left.

Parameters

check-drives.ps1 [[-MinLevel] <Int32>] [<CommonParameters>]

-MinLevel <Int32>
    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

Notes

Author: Markus Fleschutz | License: CC0

https://github.com/fleschutz/PowerShell

Source Code

<#
.SYNOPSIS
	Checks the drive space
.DESCRIPTION
	This PowerShell script checks all drives for free space left.
.PARAMETER MinLevel
	Specifies the minimum warning level (10 GB by default)
.EXAMPLE
	PS> ./check-drives
.LINK
	https://github.com/fleschutz/PowerShell
.NOTES
	Author: Markus Fleschutz | License: CC0
#>

param([int]$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
        if ($Bytes -lt 1000) { return "$($Bytes)PB" }
        $Bytes /= 1000
        if ($Bytes -lt 1000) { return "$($Bytes)EB" }
}

try {
	$Drives = Get-PSDrive -PSProvider FileSystem 
	foreach($Drive in $Drives) {
		$ID = $Drive.Name
		$Details = (Get-PSDrive $ID)
		[int64]$Free = $Details.Free
 		[int64]$Used = $Details.Used
		[int64]$Total = ($Used + $Free)

		if ($Total -eq 0) {
			"✅ Drive $ID is empty."
		} elseif ($Free -lt $MinLevel) {
			"⚠️ Drive $ID has only $(Bytes2String $Free) of $(Bytes2String $Total) left to use!"
		} elseif ($Used -lt $Free) {
			"✅ Drive $ID uses $(Bytes2String $Used) of $(Bytes2String $Total)."
		} else {
			"✅ Drive $ID has $(Bytes2String $Free) of $(Bytes2String $Total) left."
		}
	}
	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