我们的PowerShell对象包含PSCustomObjects
形式的array
。要将此信息导出到文本或Excel文件,我们需要能够展平数据。
示例代码:
$Fruits = [PSCustomObject]@{
Name = 'Banana'
Colors = [PSCustomObject]@{
Name = 'Green'
},
[PSCustomObject]@{
Name = 'Yellow'
}
Taste = [PSCustomObject]@{
Name = 'Good'
},
[PSCustomObject]@{
Name = 'Bad'
},
[PSCustomObject]@{
Name = 'Awful'
}
}
生成:
$Fruits | fl *
Name : Banana
Colors : {@{Name=Green}, @{Name=Yellow}}
Taste : {@{Name=Good}, @{Name=Bad}, @{Name=Awful}}
为了能够进行干净的导出,所需的结果应该是这样的:
Name | Color | Taste
---- | ----- | -----
Banana | Yellow | Good
Banana | Green | Bad
Banana | | Awful
怎么可能解开这个对象?
答案 0 :(得分:2)
您需要找到具有最多值的列,并将其用作for- / while循环的限制。实施例
$maxLines = $Fruits.psobject.Properties | Where-Object { $_.TypeNameOfValue -match 'Object\[\]|ICollection' } | Foreach-Object { $_.Value.Count } | Sort-Object -Descending | Select-Object -First 1
0..($maxLines-1) | ForEach-Object {
New-Object psobject -Property @{
Name = $Fruits.Name
Color = $Fruits.Colors[$_] | Foreach-Object { $_.Name }
Taste = $Fruits.Taste[$_] | Foreach-Object { $_.Name }
}
} | Select-Object Name, Color, Taste
输出:
Name Color Taste
---- ----- -----
Banana Green Good
Banana Yellow Bad
Banana Awful