Add Custom Properties

by Jan 4, 2009

While objects contain a wealth of information, this information sometimes isn't in the right format. Let's take WMI objects representing disk drives. All size properties return bytes so you may want to show megabytes or gigabytes:

Get-WMIObject Win32_LogicalDisk | Format-Table Name, Size, FreeSpace -autosize

You can. Simply add your own properties to Format-Table. To do that, add script blocks in curly braces. Inside the braces, $_ represents the object you are outputting. The next line returns sizes in megabytes:

Get-WMIObject Win32_LogicalDisk | Format-Table Name, {$_.Size/1MB}, {$_.FreeSpace/1MB} -autosize

Unfortunately, the column headers now show your script code, and also there are way too many digits after the decimal. You can fix the column header by creating a hash table and supplying the formatting you want to occur:

$column1 = @{label='Total Size (MB)'={[int]($_.Size/1MB)}}
$column2 = @{label='Free Space (MB)'={[int]($_.FreeSpace/1MB)}}

Then, supply the hash table to Format-Table:

Get-WmiObject Win32_LogicalDisk | Format-Table name, $column1, $column2 -autosize

This solved both problems as the column headers are more readable, and the digits after the decimal are gone because the result was converted to the Integer type using [Int].