PowerShell Tip: Code Check for Disk Free Space

Question

Why am I getting Aattempted to divide by zero while checking disk space? My code is below:

Get-WmiObject win32_logicaldisk | where-object {$_.Freespace -ge ((($_.freespace/$_.size) * 100)
) -and $_.drivetype -eq 3}

Answer

Indeed, yes, this will end with exception. Perfect filtering and factoring issue.

PowerShell Tip

Learned this in TechNet forum. To be more precise while scripting we should collect, filter, and aggregate before formatting.

Normal Approach

$thresholdspace = 10
Get-WMIObject  -ComputerName localhost Win32_LogicalDisk -Filter 'DriveType=3' | 
Select *, @{n='PercentFree';e={$_.freespace/$_.size*100}} |
Where-Object{$_.PercentFree -gt $thresholdspace }

Programmatic Approach and Best Practice

$thresholdspace = 50
Get-WMIObject  -ComputerName localhost Win32_LogicalDisk -Filter 'DriveType=3' | 
Select *, @{n='PercentFree';e={$_.freespace/$_.size*100}} |
Where-Object{$_.PercentFree -gt $thresholdspace } |
Select @{N='Computer';E={$_.__SERVER}},
DriveType, 
VolumeName, 
Name, 
@{n='Size (Gb)' ;e={"{0:n2}" -f ($_.size/1gb)}},
@{n='FreeSpace (Gb)';e={"{0:n2}" -f ($_.freespace/1gb)}}, 
@{n='PercentFree';e={"{0:n2}" -f $_.PercentFree}}