Tatiana Racheva
Tatiana Racheva

Reputation: 1304

PowerShell: best way to escape double quotes in string passed to an external program? E.g., a JSON string

I read I think all the articles on escaping strings in PowerShell, but I still haven't found the solution that would satisfy me.

Suppose I have a file foo.json that contains a JSON string. I need to pass the JSON string to a program as an argument.

In bash, this works just fine:

myprogram "$(cat ~/foo.json)"

In PowerShell, when I read the contents of the file normally and pass it in, the receiving program complains about there not being quotes around the keys and the values.

What I've come up with is:

$json = (get-content ~/foo.json | Out-String) -replace '"','""' myprogram $json

Is there a less awkward way to do this in PowerShell? I've resorted to exiting the session, running the command in bash, then starting the session again.

Upvotes: 5

Views: 11355

Answers (2)

mklement0
mklement0

Reputation: 437110

Unfortunately, PowerShell's passing of arguments with embedded double quotes to external programs is broken up to PowerShell 7.2.x, requiring you to manually \-escape them as \":

  • See this answer for more information about the underlying problem.

A robust workaround requires not only replacing all " with \", but also doubling any \ immediately preceding them.

# Note: If your JSON has no embedded *escaped* double quotes
#       - \" - you can get away with: -replace '"', '\"'
myprogram ((Get-Content -Raw ~/foo.json) -replace '(\\*)"', '$1$1\"')

Note the use of Get-Content -Raw, which is preferable to Get-Content ... | Out-String for reading the entire file into a single, multi-line string, but note that it requires PSv3+.


Assuming that your JSON contains either no escape sequences at all or only instances of \", a simpler workaround, discovered by Vivere, is to encode the JSON strings as JSON again, via ConvertTo-Json:

# Works, but only if your JSON contains no escape sequences
# such as \n or \\
myprogram (Get-Content -Raw ~/foo.json | ConvertTo-Json)

Upvotes: 16

In my case, I´ve replaced all double quotes by single quote before call the parameter, and set double quote just in the beggining and in the end. Worked like a charm in Powershell Script.

In my scenario, I was calling Powershell from groovy.

changeorderParam is where I have my Json string.

changeorderParam = changeorderParam.replaceAll("\"", "'")
bat "powershell.exe -Executionpolicy bypass -file C:\\\scripts\\\script.ps1 \\\"${template}\\\" \\"${script}\\" \\"${branch}\\" \\"${changeorderParam}\\""  

I hope this help someone!

Upvotes: 0

Related Questions