PowerShell - Free Disk Space

Dec 16, 2008 at 8:49 PM
Edited Dec 16, 2008 at 8:52 PM
First off, I have to say I really love PolyMon.  I believe this will be replacing What's Up Gold in our office.  I realize the PolyMon has a disk space monitor, but I like this solution better because I believe it will be easier to work with.  With PolyMon, you have to create a new monitor for each individual drive on each server.  Most will have the same low disk space values, but some will differ.  I am offering up this script, which allows one monitor to monitor all physical disks on all servers.  This is my first power-shell script, so I welcome any suggestions, improvements, etc.

-John


#
# free_disk.ps1
# -John Taylor
# Dec-16-2008
#
# This script is for PolyMon. It checks a list of servers and see if any of their fixed
# drives have less than 2 GB free. Gracefully handle the case when you can not connect
# to a server
#
# warning if disk < 2048 MBs
# failure if disk < $fail_thresh MBs
#

$servers = @("alpha", "beta", "gamma", "delta", "epsilon", "zeta" )

# special cases -- report on these server/disk combinations if their values fall below their defined value
# -- use a value of -1 to skip checking completely
# notation: server period upper-cased-drive-letter colon
$special = @{ "beta.K:" = 100; "gamma.D:" = 384; "zeta.C:" = 1300 }

$MB=1024*1024
$fail_thresh = 550
$warnings = 0
$failures = 0
$msg = "`r`n`r`n"


$count_svr=0

foreach( $svr in $servers ) {
$err=@()
$data = get-wmiobject -computer $svr -query "Select * from win32_logicaldisk where DriveType=3 and 2147483648 > FreeSpace" -ea silentlycontinue -ErrorVariable +err | Select-Object DeviceId,FreeSpace
if( $err.count ) {
$msg += "$svr (cant connect to server) -1 MB" + "`r`n"
$failures += 1
$err=@()
} else {
foreach($drive in $data) {
$recheck=0
if( $drive.DeviceID.length ) {
$test = $svr + "." + $Drive.DeviceID
if( $special.ContainsKey($test) ) {
$val = [int] $special.Get_Item($test)
#write-host "val:" + $val + " " + $svr
if( -1 -eq $val ) {
$msg += "(skipped: " + $svr + ", " + $Drive.DeviceID + ")`r`n"
continue;
} else {
$fail_thresh = $val
$recheck=1
}
}
$in_megs = [float] $drive.FreeSpace / $MB
$in_megs = "{0:#.##}" -f $in_megs
#write-host "rechk:" + $recheck + " " + $svr
if( 1 -eq $recheck ) {
if( $fail_thresh -lt [int] $in_megs ) {
#write-host "*** cmp:" + $fail_thresh + ", " + $in_megs
$recheck = 0
continue;
}
}

$msg += $svr + " " + $drive.DeviceID + " " + $in_megs + " MB" + "`r`n"

if( $fail_thresh -lt [int] $in_megs ) {
$failures += 1
} else {
$warnings += 1
}
}
}
$count_svr += 1
}
}

$msg += "`r`nFailures: " + $failures + ", Warnings: " + $warnings + "`r`n"
#write-host $msg

if( $failures ) {
$Status.StatusID=3
$Status.StatusText=$msg
} elseif( $warnings ) {
$Status.StatusID=2
$Status.StatusText=$msg
} else {
$Status.StatusID=1
$Status.StatusText="servers: " + $count_svr
}