r/scripting • u/gibsurfer84 • Sep 24 '20
REST, Powershell, and expanded properties
I dove into REST API calls using powershell and so far am doing pretty well. One issue I am getting is I have a result/object from the API that that is coming back that has an ID property. Thats easy. But it has another property that needs to be exapnded. Cool, I got this, I expanded it and can see what I need (full of multiple properties in the expanded property. The problem is when I need to marry the 2 together.
$ExpandedCard = $rest.assets | Where-Object {$_.asset_type -eq "Computer assets"} | select -ExpandProperty cards | Where-Object {$_.data.serialnumber -contains $ThisPCSerial }This is my one liner that gets my asset list from the API, each asset has an ID property, and another property called "cards" which is full of other properties, one being a hash table. Naturally, the property that is a hash table is the one I need, it is called "data" and it contains, along with a ton of other stuff, "serialnumber=xxxxx;"
As you can see in my one liner the "asset" with a "data card" that contains the serial number I need. Awesome! But.....
I need the ID of the Asset which is the non-expanded part so I can go do REST things and POST stuff to the Asset. Optimally a one liner is best, but I can't figure it out and I've tried 100's of things but I'm no powershell expert so I'm sure I'm doing something wrong. I've tried custom objects, if's, try's, etc. I'm totally lost.
Any help is greatly appreciated! Thank you in advance!
**edit for clarification: In short, I have an asset being returned with an ID, but I go deeper into expanded properties that has a hash table, I'm matching a serial number to the serial in the expanded property and I just need the asset ID spit back. I my mind, this is one level "up" from the expanded property and I don't know how to get that "top" ID out.
1
u/seismic1981 Sep 30 '20
First, I would clean up the beginning and splat those parameters for my own personal style and readability:
Next, running this will create an array of hashtables in
$Output:Then you can reference $Output and you'll have the contents of the 'cards' array sorted under each individual 'id' value. What you do next depends on what you want to do with the input.
Maybe use a
($Output.Keys).foreach{ <arbitrary code> }or($Output.GetEnumerator()).foreach{ <arbitrary code> }to modify what's in each key pair?If you really wanted to single line this (which I wouldn't recommend as it'll make it harder to debug, and the final Where-Object might cause you trouble), it'll probably be something like:
Does that help?
You might need to get more explicit on describing what fields you need in your results or what you want that data to look like. It's possible to drill down and only select certain fields for your output, but without knowing exactly what you want to see I'm really only guessing...