繁体   English   中英

在 powershell -Command 中转义双引号

[英]Escape double quotes in powershell -Command

由于某些限制,我必须从 Windows 命令提示符执行 Power Shell 命令

powershell -Command "(gc C:\my_configuration.conf) -replace 'INSERT_URL', \`"https://mytestserver/WW48.2'22/testing.bin\`" | Out-File C:\my_configuration.conf"

但是,我不断收到如下所示的ParserError

The string is missing the terminator: '.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

我应该如何用双引号正确地包裹 URL 字符串? 谢谢回答。

删除"之前的` ,您的命令应该可以工作;也就是说,当从cmd.exe / PowerShell 外部调用powershell.exe时,请使用\"而不是\`" (或`"以转义"字符。:

powershell -Command "(gc C:\my_configuration.conf) -replace 'INSERT_URL', \"https://mytestserver/WW48.2'22/testing.bin\" | Out-File C:\my_configuration.conf"

虽然您确实需要转义嵌入在整个"..."命令字符串中的"字符,但将它们转义\"就足够了 - 无需同时使用` 、反引号、PowerShell 常用的转义字符

PowerShell CLI ( powershell.exe ) 期望对"进行\转义,以便更好地与大多数 CLI 保持一致,即使在 PowerShell 会话中您需要使用`"或(仅在"..."内) "" [1]

您只需要\` - 形式为`\" ,请注意`排在第一位- 如果您嵌入的"..."本身包含"字符; 一个人为的例子:

:: OK: Prints '3" of snow.'
powershell.exe -c " Write-Output \"3`\" of snow.\" "

正如iRon指出的那样,另一种解决方案是使用嵌入式'...'引号(单引号)。

由于您的 URL 本身包含一个'字符,因此必须将该字符转义为''

:: Note the use of '...' around https://... and the inner ' escaped as ''
powershell -Command "(gc C:\my_configuration.conf) -replace 'INSERT_URL', 'https://mytestserver/WW48.2''22/testing.bin' | Out-File C:\my_configuration.conf"

[1] 在PowerShell (Core) 7+中,其 CLI 为pwsh.exe ,您也可以在命令行上使用"" inside overall "..." on the command line too, which is actually the more robust choice when calling from . When calling from cmd.exe . When calling powershell.exe 时, the robust choice is “^” (sic) - see [this answer](https://stackoverflow.com/a/49060341/45375). However, the PowerShell CLI recognizesin _both_ editions, andalso works forchars. _not_ inside overall chars. _not_ inside overall “...”内。

尝试使用此语法,总是有效

"%windir%\System32\WindowsPowerShell\v1.0\powershell.exe" -Command "& { <# PUT ANYTHING HERE #> }"

你不需要担心逃避任何事情。

你的代码:

"%windir%\System32\WindowsPowerShell\v1.0\powershell.exe" -Command "& { (gc C:\my_configuration.conf) -replace 'INSERT_URL', "https://mytestserver/WW48.2%2722/testing.bin" | Out-File 'C:\my_configuration.conf' }"

EDIT1:在此处检查 URL 特殊字符。 单引号 (') 可以通过硬编码字符串中的替换 (%27) 来处理。 (我在上面的第二个代码示例中更改了它)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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