简体   繁体   English

从 cmd.exe 调用 powershell.exe 时如何处理单引号

[英]How do deal with single quotes when invoking powershell.exe from cmd.exe

Please see sample below which fails to work due to how cmd.exe interprets single quotes looks like.请参阅下面的示例,由于 cmd.exe 解释单引号的方式,该示例无法正常工作。

powershell.exe -Command "& {param($a) ConvertFrom-JSON $a }" -a '{"name":"greg"}'

C:\>powershell.exe -Command "& {param($a) ConvertFrom-JSON $a }" -a '{"name":"greg"}'
ConvertFrom-JSON : Invalid JSON primitive: greg.
At line:1 char:14
+ & {param($a) ConvertFrom-JSON $a } -a '{name:greg}'
+              ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
  • The Windows PowerShell CLI ( powershell.exe ) requires " chars. that are to be preserved as such to be escaped as \" . Windows PowerShell CLI ( powershell.exe ) 需要" chars. that are to be reserved as such as 转义为\" [1] [1]

    • Note: PowerShell (Core) 7+ 's CLI ( pwsh.exe ) now also accepts "" , which when calling from cmd.exe is actually preferable for robustness.注意: PowerShell (Core) 7+的 CLI ( pwsh.exe ) 现在也接受""当从cmd.exe调用时,它实际上更适合健壮性。 [2] [2]
  • There is no point in trying to split the CLI arguments into a PowerShell script block and its arguments, because the PowerShell CLI simply stitches together multiple arguments - after stripping syntactic enclosing double quotes - into a single, space-separated string and then evaluates the result as PowerShell code. There is no point in trying to split the CLI arguments into a PowerShell script block and its arguments, because the PowerShell CLI simply stitches together multiple arguments - after stripping syntactic enclosing double quotes - into a single, space-separated string and then evaluates the result作为 PowerShell 代码。

Therefore, try the following:因此,请尝试以下操作:

C:\>powershell.exe -Command "ConvertFrom-JSON '{\"name\":\"greg\"}'"

name
----
greg


[1] By contrast, PowerShell- internally it is ` , the backtick, that serves as the escape character. [1] 相比之下,PowerShell - 在内部` ,即反引号,用作转义字符。

[2] Eg pwsh.exe -c " Write-Output ""a & b"" " outputs a & b , as expected, whereas [2] 如pwsh.exe -c " Write-Output ""a & b"" "输出a & b ,而
pwsh.exe -c " Write-Output \"a & b\" " fails , because cmd.exe - due to not recognizing \" as an escaped " - considers the & unquoted and therefore interprets it as its statement separator . pwsh.exe -c " Write-Output \"a & b\" "失败,因为cmd.exe - 由于未将\"识别为转义" - 认为&未加引号,因此将其解释为其语句分隔符

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

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