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.

0

1 Answer 1

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}' 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Glad to hear it, @FredrikEk.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.