1

I want to do the following call in a powershell script file:

Invoke-WebRequest -UseBasicParsing -Uri https://myservice.com `
  -ContentType application/json -Method POST `
  -Body '{"jsonproperty1": 200, "jsonproperty2": 1}'

This script works perfectly fine when executed in a powershell. However when I try to run it as:

powershell -C 'Invoke-WebRequest -UseBasicParsing -Uri https://myservice.com -ContentType application/json -Method POST -Body '{"jsonproperty1": 200, "jsonproperty2": 1}''

I can't seem to get it to work. I saw this question, but the answer there doesnt work in my case. I have tried all possible combinations of ', " and `,using different escaping techniques, that I can think of. But I keep getting 400 Bad Request from my API, which I assume is because the jsonbody cant be serialized.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Fredrik Ek
  • 623
  • 1
  • 6
  • 10

1 Answers1

2

There are two problems with your powershell -C command line:

  • You're using embedded ' chars. inside your overall '...' command string without escaping them; escape them as ''.

  • Sadly, you additionally need to \-escape the embedded " chars., even though you shouldn't have to; this answer explains why.

Therefore:

powershell -C 'Invoke-WebRequest -UseBasicParsing -Uri https://myservice.com -ContentType application/json -Method POST -Body ''{\"jsonproperty1\": 200, \"jsonproperty2\": 1}'''

However, you can avoid these quoting headaches by passing a script block ({ ... }) to the PowerShell CLI, but note that this only works from inside PowerShell):

# Use a script block, which requires no escaping.
powershell { 
  Invoke-WebRequest -UseBasicParsing -Uri https://myservice.com `
     -ContentType application/json -Method POST `
     -Body '{"jsonproperty1": 200, "jsonproperty2": 1}' 
}
mklement0
  • 382,024
  • 64
  • 607
  • 775