Beefcake
Beefcake

Reputation: 801

How to format PowerShell multidimensional array with Format-Table

I would like to send an output of a PowerShell multidimensional array using Format-Table.

Here is my sample code:

$a = ('mickey', 1,'pluto'),('qwer', 2, 'fluffy'),('prague', 1, 'new york')

foreach ($i in $a) {
    $value = 0
    if (($i[0] -eq 'mickey') -and ($i[2] -eq 'asdf')) {
        $i[1]++
        break
    } else {
        $value = 1
    }
}


if ($value -eq 1) {
    $a += ,@('mickey', 1, 'asdf')
    $value = 0
}

$a

Which would output:

mickey
1
pluto
qwer
2
fluffy
prague
1
new york
mickey
1
asdf

I would like to format this output using PowerShell Format-Tables. The separation looks neat and tidy, and the code I'm sending to it is larger than what you see.

I know I can use foreach and loop over it with the text side by side:

for ($i=0; $i -lt $a.length; $i++) {
    $a[$i][0] + " " + $a[$i][1] + " " + $a[$i][2]
}

However the output view is not what I like, and something like a header for each section would be nice.

I was thinking of something like this , but alas I could not get it to work: $a | Format-Table -Property @{Name = 'Name'; Expression = {$_[0]}; Width = 20; Align = 'left'}

Any ideas/guidance welcome.

Upvotes: 1

Views: 1943

Answers (1)

zett42
zett42

Reputation: 27756

Define the properties that will make up the table columns through Select-Object and only afterwards pass to Format-Table. The Format-Table cmdlet requires an object (e. g. [PSCustomObject]) as input, which Select-Object generates.

$a | Select-Object -Property @{ Name = 'Name'; Expression = { $_[0] } } |
     Format-Table -Property @{ Expression = 'Name'; Width = 20; Align = 'left' }

We use a trick to simplify the Format-Table line. By assigning a string instead of a scriptblock to Expression, we select the column to which formatting shall be applied. This is equivalent to:

Format-Table -Property @{ Name ='Name'; Expression = { $_.Name }; Width = 20; Align = 'left' }

Output:

Name
----
mickey
qwer
prague
mickey

Upvotes: 2

Related Questions