【问题标题】:Powershell - Display multiple columns from hash tables next to each otherPowershell - 彼此相邻显示哈希表中的多个列
【发布时间】:2020-06-17 21:33:22
【问题描述】:

我的 powershell 代码:

$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 }
}

输出

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


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

期望的输出

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

我正在尝试显示两个并排的哈希表。是否可以使用 2 个哈希表?或者我应该使用两个数组?

基本上我只想显示多列,但数据不均匀,如我想要的输出所示。

任何帮助将不胜感激。

【问题讨论】:

    标签: arrays powershell formatting hashtable tabular


    【解决方案1】:

    您可以使用自定义对象执行以下操作:

    $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
    

    【讨论】:

    • 什么都不显示。尝试了 PowerShell 5.1 和 7.0.2。我什至添加了一个PAUSE 来查看是否产生任何错误,但什么也没有。
    • 你有没有在命令行中调用$output来输出?当我这样做时,它产生了预期的结果。
    • @Kulantan 做到了。感谢您指出。
    • @Kulantan 如何通过调整其中一列的宽度来格式化表格?我尝试将$output 管道化到Format-Table,并添加一个包含宽度的计算属性,但它不起作用:$output | Format-Table -Property Item, @{ Label = "Command"; Expression = { $_.Command }; Width = 20 }, Column, Result
    • 没关系。我想到了。我必须设置所有列的宽度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    相关资源
    最近更新 更多