LLI Wiki — My Digital Knowledge Base

PowerShell: free space of a network share with event log alerts

Map a share, compute the free percentage and write a Warning or Error event.

Measure the free space of a network share in PowerShell by temporarily mapping it to a drive letter, and write a warning or an error event to the Windows Application log when it drops below a threshold.

Why map a drive

Get-PSDrive reports free and used space for a drive, not for an arbitrary UNC path. A UNC path to an administrative share such as \\192.0.2.10\c$ works, but a trailing backslash (\\192.0.2.10\c$\) does not.

Script

$share = "\\fileserver\SQL"
$nwobj = New-Object -ComObject WScript.Network
$status = $nwobj.MapNetworkDrive("O:", $share)
$drive = Get-PSDrive O
$free = $drive.Free
$used = $drive.Used
$total = $free + $used
$freeInPercentage = $free / $total * 100
$freeWithoutDecimal = [math]::Round($freeInPercentage)
Write-Output "Share $share has free space of $freeWithoutDecimal %"
$status = $nwobj.RemoveNetworkDrive("O:")

$Warning = "20"
$Critical = "10"

if ($freeWithoutDecimal -le "$Critical") {
    Write-EventLog -LogName Application -Source "Network Share Monitoring" -EntryType Error -EventID 210 -Message "The Share $Share has disk space below 10 % and Current value is $freeWithoutDecimal %"
}
elseif ($freeWithoutDecimal -le "$Warning") {
    Write-EventLog -LogName Application -Source "Network Share Monitoring" -EntryType Warning -EventID 210 -Message "The Share $Share has disk space below 20 % and Current value is $freeWithoutDecimal %"
}

Notes

Mastodon LLIMastodon SocialFosstodon