Ale*_*lex 4 powershell recursion object
我需要一种方法(递归地)为我提供对象的所有属性。不知道传输的对象有多少个子对象。
示例对象:
$Car = [PSCustomObject] @{
Tire = [PSCustomObject] @{
Color = "Black"
Count = 4
}
SteeringWheel = [PSCustomObject]@{
Color = "Blue"
Buttons = 15
}
}
Run Code Online (Sandbox Code Playgroud)
太感谢了!
Mat*_*sen 10
使用隐藏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
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出(带有示例对象层次结构):
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
Run Code Online (Sandbox Code Playgroud)
请注意,上面显示的函数不会努力防止无限循环递归引用,因此:
$a = [pscustomobject]@{b = [pscustomobject]@{a = $null}}
$a.b.a = $a
Resolve-Properties $a
Run Code Online (Sandbox Code Playgroud)
会让你的CPU旋转