3

#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.

Filed in: Columns, Tips and Tricks Tags: , ,

3 Responses to "#PSTip Advanced object formatting"

  1. Greg Wojan says:

    Shay, cool tip. 🙂 Might I make a suggestion? Could you please document whether or not the tip is new feature of PowerShell v3 or also works with v2? This tip actually works in v2 and it’s one of those great many things I just never noticed.

  2. Jaap Brasser says:

    If you would like to achieve similar results using Select-Object you can use the ToShortDateString method or ToString method. Here is an example of what that would look like:

    Get-Process | Select-Object Name,@{n=’StartDate’;e={$_.StartTime.ToShortDateString()}

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: