PowerShell: Identify if disk usage is more than 80%

1.9k views Asked by At

I'm trying to get the disk usage from all disks and then send out an email if the disk usage is more than 80% for any of the disks. Using the existing articles, I came up with the below but not able to filter out disks with more than 80% usage. Can some kind soul guide me? TIA

$size = @{label="Size(GB)";expression={[int]($_.Size/1GB)}}

$freeSpace = @{label="FreeSpace(GB)";expression={[int]($_.FreeSpace/1GB)}}

$freeSpacePercent = @{label="FreeSpace(%)";expression={[int]($_.FreeSpace/$_.Size * 100)}}

Get-CimInstance -ClassName Win32_LogicalDisk | 
Select-Object -Property DeviceID,VolumeName,$size,$freeSpace,$freeSpacePercent
1

There are 1 answers

1
Steven On BEST ANSWER

Just add a Where-Object{}, something like:

$size             = @{label = "Size(GB)"; expression = {[int]($_.Size/1GB)}}
$freeSpace        = @{label = "FreeSpace(GB)"; expression = {[int]($_.FreeSpace/1GB)}}
$freeSpacePercent = @{label = "FreeSpace(%)"; expression = {[int]($_.FreeSpace/$_.Size * 100)}}

Get-CimInstance -ClassName Win32_LogicalDisk | 
Select-Object -Property DeviceID,VolumeName,$size,$freeSpace,$freeSpacePercent |
Where-Object{ $_."FreeSpace(%)" -le 20 }

Notice it's less than 20%. Also notice the quotes, because you used special characters in the property name.

Also, you are casting to an [Int] which is going to bankers round very roughly top the whole number. That might be intentional, but whe I do this sort of thing I like to use the `[Math]::Round() function. You can change your expressions to get that:

$size             = @{label="Size(GB)"; expression = { [Math]::Round( ($_.Size/1GB), 2 ) }}
$freeSpace        = @{label="FreeSpace(GB)"; expression = { [Math]::Round( ($_.FreeSpace/1GB), 2 ) }}
$freeSpacePercent = @{label="FreeSpace(%)"; expression = { [Math]::Round( ($_.FreeSpace/$_.Size * 100), 2 ) }}

Get-CimInstance -ClassName Win32_LogicalDisk | 
Select-Object -Property DeviceID,VolumeName,$size,$freeSpace,$freeSpacePercent