Gregory Suvalian
Gregory Suvalian

Reputation: 3832

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

Upvotes: 1

Views: 123

Answers (1)

mklement0
mklement0

Reputation: 440092

  • 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] E.g. 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.

Upvotes: 3

Related Questions