我需要一种方法(递归地)为我提供对象的所有属性。 不知道转移的对象有多少个子对象。
示例对象:
$Car = [PSCustomObject] @{
Tire = [PSCustomObject] @{
Color = "Black"
Count = 4
}
SteeringWheel = [PSCustomObject]@{
Color = "Blue"
Buttons = 15
}
}
非常感谢!
最佳答案
使用隐藏的psobject
成员集枚举属性,然后递归:
function Resolve-Properties
{
param([Parameter(ValueFromPipeline)][object]$InputObject)
process {
foreach($prop in $InputObject.psobject.Properties){
[pscustomobject]@{
Name = $prop.Name
Value = $prop.Value
}
Resolve-Properties $prop.Value
}
}
}
输出(带有示例对象层次结构):
PS C:\> Resolve-Properties $Car
Name Value
---- -----
Tire @{Color=Black; Count=4}
Color Black
Length 5
Count 4
SteeringWheel @{Color=Blue; Buttons=15}
Color Blue
Length 4
Buttons 15
请注意,上面显示的函数没有努力防止无限循环递归引用,因此:
$a = [pscustomobject]@{b = [pscustomobject]@{a = $null}}
$a.b.a = $a
Resolve-Properties $a
会让你的 CPU 旋转
关于PowerShell 递归对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63152449/