33

I need to send a simple string to a web api using Powershell, and I have to ensure the value in the HTML body has "Quotes" around it, because the content type has to be application/json.

For example:

$specialKey = "101010"
Invoke-RestMethod -Method Put `
                -Uri $keyAssignmentUri `
                -Header @{"content-type"="application/json"} `
                -Body "$specialKey"

When I inspect this call in Fiddler, I see that the body is 101010 instead of "101010". How do I send the body value with quotes?

3
  • 1
    -body ($specialKey | ConvertTo-Json) ? Commented Jun 30, 2017 at 7:19
  • 1
    Useful blog on quotation marks Commented Jun 30, 2017 at 9:26
  • I wish PowerShell had Python like r'' or """long multiline triple quote """! Commented Mar 13, 2023 at 14:17

3 Answers 3

56

In order to have the "Quotes", you need to provide the escape character (`) before every " which you want to print or send.

$PrintQuotesAsString = "`"How do I escape `"Quotes`" in a powershell string?`"" 

Write-Host $PrintQuotesAsString 

"How do I escape "Quotes" in a powershell string?"

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Nice solution !
17

Replacing double quotes (") with a sequence of back-slash, backtick and double-quotes worked for me:

\`"

Example: I want to set (using the env command) an environment variable named SCOPES to the following value, then launch node app.js:

{
   "email":"Grant permissions to read your email address",
   "address":"Grant permissions to read your address information",
   "phone":"Grant permissions to read your mobile phone number"
}

so I used:

env SCOPES="{ \`"email\`": \`"Grant permissions to read your email address\`",   \`"address\`": \`"Grant permissions to read your address information\`",   \`"phone\`": \`"Grant permissions to read your mobile phone number\`" }" node app.js

References: http://www.rlmueller.net/PowerShellEscape.htm

Comments

14

Assuming you don't need to do variable substitution in your string, a simple solution is to just surround it with single quotes to make it a literal string:

$specialKey = '"101010"'

4 Comments

If you have variables in your string such as $string = 'Found $count records in "test" file' then this is not a solution as the variable value won't print to the string. Dipanjan's answer, below, works though.
I agree this shouldn’t be the accepted answer. It’s a potential solution for some scenarios but it’s not the right answer to the question.
Seems like powershell 7.3.0 breaks this feature. Use '\"101010\"' instead
In PowerShell 7.4 '"101010"' worked for me. link

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.