2

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
2
  • 1
    You could use one of the resources from the MS powershelgallery.com, vs doing this from scratch (unless this is a learning exercise/homework question --- ;-} ). From your PowerShell session, just type. Find-Module -Name '*disk*' or one of the scripts, Find-Script -Name '*disk*' Commented Apr 20, 2021 at 22:08
  • Thx for the reference to powershellgallery. Am adding it to my favorites. Commented Apr 21, 2021 at 21:15

1 Answer 1

4

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks much Steven.. worked like a charm. I knew I had to use "where-object" but wasn't quite there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.