Author Posts

August 8, 2016 at 8:56 pm

I have two related questions regarding formatting arrays of strings ($array1, $array2, $array3) into a table.

1. What's the easiest way to sort them into columns, each with their own heading? For example,

ColumnA ColumnB etc...
——– ——–
A A
B B
C C

I tried:

$table = @( @{ ColumnA="$array1"; ColumnB="$array2"; ColumnC="$array3"})
$table.ForEach({[PSCustomObject]$_}) | Format-Table -AutoSize

But the elements form rows, not columns.

2. As a second step, how would I convert this table to html with a header and borders? For example,

HEADER

ColumnA ColumnB etc...
——– ——–
A A
B B
C C

I've gotten this to work before, but the solution was a little messy, so I want to see what the cleanest way is.

Thanks for any help.

August 8, 2016 at 9:18 pm

So, the easiest would be to create custom objects, since that's what PowerShell actually deals best with.

$properties = @{ 'ColumnA' = 'ValueA'
                 'ColumnB' = 'ValueB' }

Those can then be piped to ConvertTo-HTML. However, that cmdlet doesn't support formatting. For fancy HTML formatting, read "Creating HTML Reports in PowerShell," right here on our lovely eBooks menu item. There's a good example about producing objects for the cmdlets to consume. Arrays are kind of "meh" in PowerShell.

August 8, 2016 at 9:56 pm

I think he was asking about joining the arrays so they are in their own column. Possible but not really necessary.

Two arrays with equal numbers is the best way to show this. I'll let you deal with uneven counts for homework:-)

$array1 = (1..10)
$array2 = (11..20)

0..($array1.Length-1) | Select @{n="one";e={$array1[$_]}}, @{n="two";e={$array2[$_]}}