W2KSG: Free Disk Space

Nope - not a 1960's political slogan.

Previously we found out how to discover the logical disk drives on our machines.  Having found them we want to know how much free space is available.

Listing 10.6

$HardDisk = 3
Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType = $HardDisk" | Format-Table DeviceId, @{Label="Freespace(GB)"; Expression={($_.FreeSpace/1GB).ToString("F04")}} -auto

We start by defining a variable. The value of 3 indicates it is a local disk.  Using Get-WmiObject -Class Win32_LogicalDisk again we apply a filter this time.  This is like running a WQL query but we don't need the SELECT * FROM classname WHERE bits.  We could have put the value directly into the filter but its more fun to do it this way.

Pipe the results straight into Format-Table displaying DeviceId (drive letter) and using a calculated field to derive the freespace in GB (its produced in bytes). A calculated field is a hash table where we define a label for the field and an expression to calculate the required result. In this case take the freespace & divide by 1GB (how easy  is that) and then to make a nice display we convert to a string and user a formatter to restrict it to 4 decimal places. The -auto places the info on screen in a sensible manner rather the two columns being at opposite sides of the screen.

Certainly takes longer to explain than to run!

 

Share this post :

 

Technorati Tags: ,

Leave a Reply