Search code examples
powershellobjectrecursion

PowerShell recursive object properties


I need a method that gives me all the properties of an object (recursively). It is not known how many sub-objects the transferred object has.

Example object:

$Car = [PSCustomObject] @{
    Tire          = [PSCustomObject] @{
        Color = "Black"
        Count = 4
    }

    SteeringWheel = [PSCustomObject]@{
        Color   = "Blue"
        Buttons = 15
    }
}

Thank you so much!


Solution

  • Use the hidden psobject member set to enumerate the properties, then recurse:

    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
        }
      }
    }
    

    Output (with your sample object hierarchy):

    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
    

    Be careful, the function shown above makes no effort to protect against infinitely looping recursive references, so:

    $a = [pscustomobject]@{b = [pscustomobject]@{a = $null}}
    $a.b.a = $a
    Resolve-Properties $a
    

    Will send your CPU spinning