68

How do you format an array of hash tables with the Format-Table cmdlet?

Example:

$table = @( @{ColumnA="Able";    ColumnB=1},
            @{ColumnA="Baker";   ColumnB=2},
            @{ColumnA="Charlie"; ColumnB=3} )
$table | Format-Table

Desired Output:

ColumnA                        ColumnB
----                           -----
Able                           1
Baker                          2
Charlie                        3

Actual Output:

Name                           Value
----                           -----
ColumnA                        Able
ColumnB                        1
ColumnA                        Baker
ColumnB                        2
ColumnA                        Charlie
ColumnB                        3

2 Answers 2

99

Using Powershell V4:

$table = @( @{ColumnA="Able";    ColumnB=1},
            @{ColumnA="Baker";   ColumnB=2},
            @{ColumnA="Charlie"; ColumnB=3} )

$table | ForEach {[PSCustomObject]$_} | Format-Table -AutoSize


ColumnA ColumnB
------- -------
Able          1
Baker         2
Charlie       3

V2 solution:

$(foreach ($ht in $table)
 {new-object PSObject -Property $ht}) | Format-Table -AutoSize
Sign up to request clarification or add additional context in comments.

7 Comments

Do you need a V2-specific solution?
It would be nice, but I can upgrade to V4 if that is what it takes. Can you do it in V2?
PS2 way shorter: $table| % { new-object PSObject -Property $_}
Adding Format-Table back to @majkinetor solution, makes formatting nicer $table| % { new-object PSObject -Property $_} | Format-Table -AutoSize
I found the provided foreach syntax a little awkward, but it pointed me in the right direction. -- I ended up using this syntax $table | % { [PSCustomObject]$_ } | Format-Table
|
2

Discovered an alternative way of doing this:

$table | Select-Object -Property (
    $table.Keys | Group-Object | Select-Object -ExpandProperty Name)

But compared to @mjolinor's answer, doing this is:

  • More verbose
  • Slower, by about an order of magnitude, based on quick test of 10,000 elements

Casting to [PSCustomObject] seems to be the right way to go.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.