PowerShell 递归对象属性

标签 powershell object recursion

我需要一种方法(递归地)为我提供对象的所有属性。 不知道转移的对象有多少个子对象。

示例对象:

$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/

相关文章:

excel - PowerShell:从 excel 文件中删除 VBA 模块

javascript - 使用 Object.assign() 时,React 组件不会重置状态?

Java:在方法内部查找对象引用

regex - 正则表达式中的 (?ms) 是什么意思?

azure - 确定 Microsoft Azure 中的虚拟机状态和事件

c++ - 我的逻辑正确吗?它给出了段错误

c++ - 需要优化 - 算法实现占用太多内存

PHP array_replace_recursive 如果是标量,array_merge_recursive 如果是数组

使用 PowerShell 部署 Azure 数据工厂管道

javascript - 如何从 Javascript 数组中删除带有空字符串的对象?