Convert Arrays to Columns in a Table

Tagged: ,

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Dan Potter Dan Potter 10 months, 3 weeks ago.

  • Author
  • #49642
    Profile photo of Brandon Lashmet
    Brandon Lashmet

    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,


    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.

  • #49650
    Profile photo of Don Jones
    Don Jones

    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.

  • #49654
    Profile photo of Dan Potter
    Dan Potter

    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[$_]}}

You must be logged in to reply to this topic.