4

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!

Alex
  • 125
  • 2
  • 12
  • Does this answer your question? [Does PowerShell support HashTable Serialization?](https://stackoverflow.com/questions/60621582/does-powershell-support-hashtable-serialization) – iRon Jul 29 '20 at 11:30
  • Related: [How do I iterate a PSCustomObject nested object?](https://stackoverflow.com/q/71720045/7571258) – zett42 Apr 06 '22 at 10:46

1 Answers1

8

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

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • I like this solution a lot, I need to do something similar, except I need to pass in a change to the original object once I find the matching prop + value. So following that example I would want to change all color properties to be red. Ideally it would be nice to update the existing object, but not really married to that thought, certainly open to returning an updated copy of that object. – Jeff Patton Nov 20 '21 at 03:28