输出具有重叠字段的数组

时间:2016-10-04 16:01:34

标签: arrays powershell

下午好, 我输出一个PowerShell自定义对象时遇到了一些麻烦。

它是一个显示人们和他们拥有什么水果的数组(信息是通过许多其他过程收集的,并且将是一个真正的PITA来改变),例如;

First, last,<fruit>
Joe, Bloggs, apple=$true, banana=$true, pear=$true
Fred, Smith, apple=$true, melon=$true, banana=$true
Mick, Jones, pear=$true, melon=$true

如果我使用     $ array | fl * 一切都很好:

First: Joe
Last: Bloggs
apple: True
Banana: True
Pear: True

First: Mick
Last: Jones
apple: True
melon: True
banana: True

First: Fred
Last: Smith
Pear: True
melon: True

不幸的是,当使用out-gridview或export-csv或$ array | ft *时,它只显示所有记录中通用的字段,例如

$array|ft *
First     Last
----      ----
Joe       Bloggs
Mick      Jones
Fred      Smith

我想要做的是显示所有组合但只是错过那些不存在的组合,

$array|ft *
First     Last     Apple     Banana     Pear     Melon
----      ----     ----      ----       ----     ----
Joe       Bloggs   True      True       True
Mick      Jones    True      True                True
Fred      Smith                         True     True

(最简单的方法就是将每个水果加入水果“每个记录/人的关键/值

First: Joe
Last: Bloggs
Fruit: {apple, banana, melon}

“但这对最终目标来说效果不太好”

提前致谢。

1 个答案:

答案 0 :(得分:1)

Format-Table使用第一个元素的属性列表,因此您需要手动构建数组中存在的所有属性的列表:

$fruits = $array | ForEach { $_.PSObject.Properties.Name -ne 'First' -ne 'Last' } |
                   Sort -unique
$properties = @('First', 'Last') + $fruits
$array | ft $properties

(以上代码适用于PS3.0 +,因此在PS2.0中使用($_.PSObject.Properties | Select -expand Name)代替$_.PSObject.Properties.Name

或修复第一个元素,以便Format-Table / Export-Csv / ConvertTo-Csv正常工作:

$missing = @{}
$array | ForEach { $_.PSObject.Properties | Select -expand Name } |
         Sort -Unique |
         Where { $array[0].$_ -eq $null } |
         ForEach { $missing.$_ = $null }
$array[0] | Add-Member -NotePropertyMembers $missing

现在cmdlet将输出所有属性:

  • $array | ft

    First Last   apple Banana Pear melon
    ----- ----   ----- ------ ---- -----
    Joe   Bloggs  True   True True      
    Mick  Jones   True   True      True 
    Fred  Smith               True True 
    
  • $array | ConvertTo-Csv -NoTypeInformation

    "First","Last","apple","Banana","Pear","melon"
    "Joe","Bloggs","True","True","True",
    "Mick","Jones","True","True",,"True"
    "Fred","Smith",,,"True","True"
    
相关问题