Outputting Calculated Properties

by Nov 21, 2008

Format-Table is a very convenient cmdlet to output data as table. You can pick the object properties you want to output like this:

Dir | Format-Table Name, Length

This would then give you a table with file names and file size in bytes. However, if you would rather see the size in kilobytes instead of bytes, you can easily append that table with calculated properties. By adding a script block in curly braces to your list of output properties and using the special variable $_ to access the objects, you can then calculate your new column:

Dir | Format-Table Name, { [int]($_.Length/1KB) } -AutoSize

You will get the calculated column, though PowerShell uses your expression as column header. To add a custom column header, you can supply the column information as a specially formatted hash table like this:

$mycolumn = @{expression={ [int]($_.Length/1KB) }; label='KB'=='left'}
Dir | Format-Table Name, $mycolumn -AutoSize