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



我有一个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"

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

您可以使用一个简单的嵌套循环为每个对象的Address属性中的每个值创建一个新对象:

$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

相关内容

  • 没有找到相关文章

最新更新