如何在PowerShell字符串中转义双引号?

22
我需要使用Powershell向Web API发送一个简单的字符串,我必须确保HTML正文中的值用引号括起来,因为内容类型必须为application/json。
例如:
$specialKey = "101010"
Invoke-RestMethod -Method Put `
                -Uri $keyAssignmentUri `
                -Header @{"content-type"="application/json"} `
                -Body "$specialKey"

当我在Fiddler中检查此调用时,我看到body的值是101010而不是"101010"。我该如何发送带引号的body值?


当我在Fiddler中检查这个请求时,我发现body的值为101010,而不是带引号的"101010"。请问该如何发送带引号的body值?

1
-body ($specialKey | ConvertTo-Json) - wOxxOm
有关引号的博客文章非常有用。 - henrycarteruk
我希望PowerShell也能像Python一样拥有r''"""长多行三引号""" - Rajesh Swarnkar
3个回答

37
为了使用引号,您需要在想要打印或发送的每个引号之前提供转义字符 (`)。
$PrintQuotesAsString = "`"How do I escape `"Quotes`" in a powershell string?`"" 

Write-Host $PrintQuotesAsString 

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

输入图片说明


好的解决方案! - M. Suurland

13

假设你不需要在字符串中进行变量替换,一个简单的解决方案是只需用单引号将其括起来,使它成为字面字符串:

$specialKey = '"101010"'

如果您的字符串中有变量,例如 $string = 'Found $count records in "test" file',那么这不是一个解决方案,因为变量值不会打印到字符串中。Dipanjan 的答案如下,可以解决这个问题。 - n8.
1
我同意这不应该是被接受的答案。对于某些情况来说,它可能是一个潜在的解决方案,但它并不是问题的正确答案。 - Mark Wragg
似乎 PowerShell 7.3.0 破坏了这个功能。请使用 '\"101010\"' 代替。 - undefined

10

对于我而言,将双引号(“)替换为反斜杠、重音符和双引号的序列是有效的:

\`"

示例: 我想要使用env命令设置一个名为SCOPES的环境变量,并将其值设置为以下内容,然后启动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"
}

所以我使用了:

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

参考文献: http://www.rlmueller.net/PowerShellEscape.htm


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接