Question:
I am trying a POST request using PowerShell. It takes body of type raw. I know how to pass form-data using PowerShell, however not sure for rawdata type. For a simple raw-data in Postman e.g.
1 2 3 4 5 6 |
{ "@type":"login", "username":"xxx@gmail.com", "password":"yyy" } |
I pass below in PowerShell and it works fine.
1 2 3 4 5 6 7 8 |
$rawcreds = @{ '@type' = 'login' username=$Username password=$Password } $json = $rawcreds | ConvertTo-Json |
However, for a complex rawdata like below, I am unsure how to pass in PowerShell.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
{ "@type": Sample_name_01", "agentId": "00000Y08000000000004", "parameters": [ { "@type": "TaskParameter", "name": "$source$", "type": "EXTENDED_SOURCE" }, { "@type": "TaskParameter", "name": "$target$", "type": "TARGET", "targetConnectionId": "00000Y0B000000000020", "targetObject": "sample_object" } ], "mappingId": "00000Y1700000000000A" } |
Answer:
My interpretation is that your second code block is the raw JSON you want, and you’re not sure how to construct that. The easiest way would be to use a here string:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
$body = @" { "@type": Sample_name_01", "agentId": "00000Y08000000000004", "parameters": [ { "@type": "TaskParameter", "name": "$source$", "type": "EXTENDED_SOURCE" }, { "@type": "TaskParameter", "name": "$target$", "type": "TARGET", "targetConnectionId": "00000Y0B000000000020", "targetObject": "sample_object" } ], "mappingId": "00000Y1700000000000A" } "@ Invoke-WebRequest -Body $body |
Variable substitution works (because we used @"
instead of @'
) but you don’t have to do messy escaping of literal "
characters.
So what that means is that $source$
will be interpreted as a variable named $source
to be embedded in the string followed by a literal $
. If that’s not what you want (that is, if you want to literally use $source$
in the body), then use @'
and '@
to enclose your here string so that powershell variables are not embedded.