Powershell将Object[]拆分为多行CSV文件

amrnrhlw  于 2022-12-06  发布在  Shell
关注(0)|答案(1)|浏览(142)

我有一个如下所示的powershell数组对象

Name    : Bob
Address : {adr1, adr2, adr3}
Phone   : 123

Name    : Alice
Address : {adr4, adr5, adr6}
Phone   : 456

我想将此对象转换为CSV文件,格式如下:

"Name","Address","Phone"
"Bob","adr1","123"
"Bob","adr2","123"
"Bob","adr3","123"
"Alice","adr4","456"
"Alice","adr5","456"
"Alice","adr6","456"

如果我在对象上使用Export-Csv,则输出如下所示:

"Name","Address","Phone"
"Bob","System.Object[]","123"
"Alice","System.Object[]","456"

如何使输出看起来像预期的输出?

carvr3hs

carvr3hs1#

您可以使用简单的巢状循环,为每个对象的Address属性中的每个值建立1个新对象:

$data |ForEach-Object {
  foreach($adr in $_.Address){
    # create 1 new object per value in $_.Address
    $_ |Select Name,@{Name='Address';Expression={$adr}},Phone
  }
} |Export-Csv output.csv -NoTypeInformation

相关问题