#PSTip Advanced object formatting

With the Format-Table cmdlet we format and display a tabular format of an output, We can also select and display output of selected properties of objects.

Get-Process | Format-Table Name,StartTime

You can also use a hash table to add calculated properties to an object before displaying it. The following command displays a table with the Name and StartTime of all processes on the local computer (not all processes have this property set). The StartTime is formatted using .NET format specifiers to display the date in mm/dd/yy format.

Get-Process | Format-Table Name,@{Name='StartDate';Expression={"{0:d}" -f $_.StartTime}}

But there’s a better, built-in, PowerShell way to do this, one that doesn’t invole the traditional .NET way of string formatting (e.g ‘{0}’):

Get-Process | Format-Table Name,@{Name='StartDate';Expression={$_.StartTime};FormatString="d"}

Using the FormatString key (available in v2 and above), all you need to do is specify the modifier itself, PowerShell will do the rest.

And as you probably know, the hash table keys can be specified by just their first letter, so the following is also valid:

Get-Process | Format-Table Name,@{n='StartDate';e={$_.StartTime};f="d"}

Note: Calculated properties can be used using the Select-Object cmdlet but unfortunately the FormatString cannot be used with it. I logged a suggestion so add your vote if you want to have this option in Select-Object.

Share on: