将对象数组拆分为行

时间:2015-02-16 14:22:25

标签: powershell

考虑一个返回对象X列表的函数,其中X有一个整数和数组对象。

Get-Foo

MyInteger   MyStrings
---------   ---------
        1   {A,B,C,D}
        2   {A,B,C}
        3   {A}

如何执行此列表的自联接以获取下面的输出?

Get-Foo

MyInteger   MyString
---------   --------
        1   A
        1   B
        1   C
        1   D
        2   A
        2   B
        2   C
        3   A

1 个答案:

答案 0 :(得分:2)

只需在每个对象上遍历MyStrings,并为每个对象创建一个新对象:

function get-foo {
[PSCustomObject]@{MyInteger=1;MyStrings=@('A','B','C','D')}
[PSCustomObject]@{MyInteger=2;MyStrings=@('A','B','C')}
[PSCustomObject]@{MyInteger=3;MyStrings=@('A')}
}

get-foo | 
foreach {
 foreach ($string in $_.MyStrings)
  { [PSCustomObject]@{
     MyInteger = $_.MyInteger
     MyString=$string
    }
   }
 } | ft -AutoSize

MyInteger MyString
--------- --------
        1 A       
        1 B       
        1 C       
        1 D       
        2 A       
        2 B       
        2 C       
        3 A       
相关问题