1

I am creating a powershell program that is supposed to check the free Disk Space of all the drives on a computer. I have found

Get-WmiObject Win32_logicaldisk |Format-Table DeviceID, freeSpace, Size

which generates the data I want in a table.

However I am not sure how to use each specific element in formulas and other parts of the program.

Ultimately I want to check every disk on the computer to see if its more than 50% free, and emit an output accordingly.

Thanks!

2 Answers 2

1

Never use the Format-* cmdlets before the point at which you need to acutally format and present the data to a user.

To grab the properties of an object without formatting it, use Select-Object:

$DiskInfo = Get-WmiObject Win32_logicaldisk |Select-Object DeviceID,FreeSpace,Size

To get the percentage of free space, you could use a calculated property:

$DiskInfo = Get-WmiObject Win32_logicaldisk |Select-Object DeviceID,@{L="FreeSpacePercentage";E={100*($_.FreeSpace/$_.Size)}},FreeSpace,Size

Since Get-WmiObject Win32_LogicalDisk returns an object per disk, $DiskInfo is now an array of objects with the exact 4 properties you selected.

Iterate over the array with a loop or the ForEach-Object cmdlet and output accordingly:

$DiskInfo |ForEach-Object {
    if($_.FreeSpacePercentage -gt 50){
        Write-Host "There's more than 50% free disk space on drive $($_.DeviceID)"
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Everything looks good, except the write-host line just displays "There's more than 50% free disk space on drive" and doesn't specify which Drive
That's just because my fat fingers can't spell DeviceID, fixed now :)
0

Try this

Get-WmiObject Win32_Volume -computername $env:computername |

Select-Object DriveType, @{Name="Size(GB)";Expression={"{0:N1}" -f($_.Capacity/1gb)}},@{Name="FreeSpace(GB)";Expression={"{0:N1}" -f($_.freespace/1gb)}},@{Name="FreeSpacePerCent";Expression={"{0:N0}" -f(100*$_.freespace/$_.capacity)}} | 
Where-Object -FilterScript {[decimal]$_.FreeSpacePerCent -gt 50 -and $_.drivetype -eq 3} |
Sort-Object -property "FreeSpacePerCent" 
Format-Table 

Comments

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.