简体   繁体   中英

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.

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 \" . [1]

    • Note: PowerShell (Core) 7+ 's CLI ( pwsh.exe ) now also accepts "" , which when calling from cmd.exe is actually preferable for robustness. [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.

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.

[2] Eg pwsh.exe -c " Write-Output ""a & b"" " outputs a & b , as expected, whereas
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 .

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