Search code examples
arrayspowershellformattinghashtabletabular

Powershell - Display multiple columns from hash tables next to each other


My powershell code:

$h1 = [ordered]@{
    "item1" = "command1"
    "item2" = "command2"
    "item3" = "command3"
    "item4" = "command4"
    "item5" = "command5"
}

$h2 = [ordered]@{
    "col1" = "result1"
    "col2" = "result2"
}

$h1.GetEnumerator() | Format-Table @{
    Label = "Item";
    Expression = { $_.Key }
}, @{
    Label = "Command";
    Expression = { $_.Value }
}

$h2.GetEnumerator() | Format-Table @{
    Label = "Column";
    Expression = { $_.Key }
}, @{
    Label = "Result";
    Expression = { $_.Value }
}

Output

Item  Command
----  -------
item1 command1
item2 command2
item3 command3
item4 command4
item5 command5


Column Result
------ ------
col1   resul1
col2   resul2

Desired Output

Item  Command  Column Result
----  -------  ------ ------
item1 command1 col1   resul1
item2 command2 col2   resul2
item3 command3
item4 command4
item5 command5

I'm trying to display two hash tables next to each other. Is it possible with 2 hash tables? Or maybe I should use two arrays?

Basically I just want to display multiple columns, but with uneven data, as shown in my desired output.

Any help would be much appreciated.


Solution

  • You can do the following using custom objects:

    $index = 0
    $output = $h1.GetEnumerator() | Foreach-Object {
        [pscustomobject]@{'Item' = $_.key; 'Command' = $_.value}
    }
    $h2.GetEnumerator() | Foreach-Object {
        $output[$index++] | Add-Member -NotePropertyMembers @{'column' = $_.key;'result' = $_.value}
    }
    $output