Using a Hash Table to format data

When you use Format-Table you can choose which columns you wish to view.

Get-WMIObject Win32_LogicalDisk -Filter "DriveType=3" | Format-Table DeviceID, FreeSpace, PercentFree

Instead of specifying just a property name you can use a Hash Table to have more control including:  What the Column header will be, calculating values to be shown and formatting the data.

Get-WMIObject Win32_LogicalDisk -Filter "DriveType=3" | Format-Table DeviceID, FreeSpace, @{Label = "Percent Free" ; Expression = {$_.FreeSpace / $_.Size}}

To control the data in the Hash Table we need to provide the following name/value pairs:

  • Label (or Name or n) / The text to be displayed in the column heading
  • Expression (or e) / The calculated value to be shown

Adding the Hash Table to the Format-Table command can lead to some long, hard to read commands.  One technique to tidy this up is to save the Hash Table as a variable first, and then to refer to the variable names in the Format-table command.

$PercentFree = @{Label = "Percent Free" ; Expression = {$_.FreeSpace / $_.Size}}
Get-WMIObject Win32_LogicalDisk -Filter "DriveType=3" | `
Format-Table DeviceID, FreeSpace, $PercentFree

If you wish, the Hash Table can also contain formatting information such as:

$PercentFree = @{Label = "Percent Free" ;Expression = {$_.FreeSpace / $_.Size};FormatString="{0:0.00%}"}
The Hash Table can also contain formatting information such as:
$PercentFree = @{Label = "Percent Free" ; Expression = {$_.FreeSpace / $_.Size}; FormatString="{0:0.00%}"}

Leave a Reply

Your email address will not be published. Required fields are marked *