简体   繁体   中英

How do I escape “Quotes” in a powershell string?

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?

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?"

在此处输入图片说明

用单引号将其括起来以使其成为文字字符串:

$specialKey = '"101010"'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM