Enumerate a PSCustomObject as key/value pairs

2.6k views Asked by At

I'm calling Invoke-RestMethod on a URI which returns JSON like this:

{
  "01": {"ID":1, "Name":"Foo"},
  "02": {...},
  "03": {...}
}

I end up with a PSCustomObject whose property names are the numbers in the keys, and values are the object graphs, but I want to treat the object as a list of key/value pairs (i.e.: a dictionary). I tried:

(Invoke-RestMethod -Uri $uri) | foreach-object {
  $_.ID
  $_.Key.ID
}

and so on; but then realized that Foreach-Object is only iterating once; the return value from Invoke-RestMethod isn't an IEnumerable

How can I get a collection of the properties and values in the result object?

1

There are 1 answers

0
Jesse Hallam On

Ended up working with this solution:

$js = (Invoke-RestMethod -Uri = $uri)
$hash = @{}
($js | Get-Member -MemberType NoteProperty).Name | Foreach-Object {
    $hash[$_] = $js.$_
}