Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate a PSCustomObject as key/value pairs

Tags:

powershell

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?

like image 370
Jesse Hallam Avatar asked Jun 09 '15 07:06

Jesse Hallam


People also ask

What is a PSCustomObject?

The [pscustomobject] type accelerator was added in PowerShell 4.0. Prior to adding this type accelerator, creating an object with member properties and values was more complicated. Originally, you had to use New-Object to create the object and Add-Member to add properties. For example: PowerShell Copy.

How do you represent a key-value pair?

A key-value pair consists of two related data elements: A key, which is a constant that defines the data set (e.g., gender, color, price), and a value, which is a variable that belongs to the set (e.g., male/female, green, 100). Fully formed, a key-value pair could look like these: gender = male. color = green.

What is a Noteproperty PowerShell?

NoteProperties are generic properties that are created by Powershell (as opposed to properties that are inherited from a specific dotnet object type).


1 Answers

Ended up working with this solution:

$js = (Invoke-RestMethod -Uri = $uri)
$hash = @{}
($js | Get-Member -MemberType NoteProperty).Name | Foreach-Object {
    $hash[$_] = $js.$_
}
like image 108
Jesse Hallam Avatar answered Oct 06 '22 00:10

Jesse Hallam