0

I have a param section of a Invoke-RestMethod that i have to keep as is, but also add parameters:

$param = @{
...
Body = '{"entry":[{"@name":SOMETEXT,"static":{"member":[ANOTHERTEXT]}}]}' 
...
}

Since the entire Body is in single quotes, any $parameter added will be treated like a string instead of a normal PowerShell parameter

In this case SOMETEXT and ANOTHERTEXT will be $HubAddressObject and $ArrayList, respectivly.

How do i make that Body entry work with parameters, and keeping the same structure (this is part of a Panorama box)?

What i would need would be:

Body = '{"entry":[{"@name":$HubAddressObject,"static":{"member":[$ArrayList]}}]}'

Thanks.

Alex
  • 75
  • 7
  • 1
    I don’t know enough about what a “Panorama box” is to understand the constraints on PowerShell scripts, but would string concatenation work? E.g. ```Body = '{"entry":[{"@name":’ + $HubAddressObject + ‘,"static":{"member":[‘ + $ArrayList + ‘]}}]}'```. If you can link to relevant docs there might be other options.. – mclayton Jun 22 '22 at 14:57
  • You could do this by using double-quotes around the whole thing and escape the in-between double quotes with a backtick: ```"{`"entry`":[{`"@name`":$HubAddressObject,`"static`":{`"member`":[$ArrayList]}}]}"```, but wouldn't it be a lot easier if you have the data as **object** and convert that to JSON like with `$MyObject | ConvertTo-Json -Compress` ?? – Theo Jun 22 '22 at 15:11
  • @mclayton - gave me the idea to rework this a bit, resulting in: `('{{"entry":[{{"@name": "{0}","static": {{"member": [{1}]}}}}]}}' -F 'SOMETEXT', 'ANOTHERTEXT')` – Alex Jun 22 '22 at 15:45

1 Answers1

1

I'd recommend using ConvertFrom-Json / ConvertTo-Json for that kind of thing.

To keep it one 1 line, you can use the -Compress switch.

$params = @{
  Body = '{"entry":[{"@name":"SOMETEXT","static":{"member":"[ANOTHERTEXT]"}}]}' 
}

# Create a PSObject representation of your JSON
$jsonObj = $Params.body | ConvertFrom-Json

#Modify whatever you want
$jsonObj.entry[0].'@name' = 'NewText'

# Convert the Object back to Json.
$Params.Body = $JsonObj | Convertto-Json -Compress -Depth 4

Json comparison

# Starting off Json
{"entry":[{"@name":"SOMETEXT","static":{"member":"[ANOTHERTEXT]"}}]}
# Modified JSON
{"entry":[{"@name":"NewText","static":{"member":"[ANOTHERTEXT]"}}]}
Sage Pourpre
  • 9,932
  • 3
  • 27
  • 39
  • This also works, tested with my own parameters i have prepared. I tried something similar initially, but this is more complex than i would've thought. Thanks. – Alex Jun 22 '22 at 15:46
  • 1
    This is better than building the json string yourself - it properly escapes characters like ```{``` and ```}``` in the variable values, which would at best cause an exception, and at worst could expose a json-injection vulnerability… – mclayton Jun 22 '22 at 17:58