The unfortunate need for manual \
-escaping of "
chars. embedded in string arguments passed to external programs is due to a long-standing PowerShell bug - see this answer - which is finally fixed in PowerShell 7.3+, with selective exceptions on Windows - see this answer.
- That is to say, you should be able to just pass
'{ "name": "Bob" }'
- no \
-escaping, but the bug prevents that.
To automate this escaping for now, without having to modify a given JSON string, you can apply a regex-based -replace
operation, namely $json -replace '([\\]*)"', '$1$1\"'
# Note: only needed for *external executables*, up to at least PowerShell 7.2.x
executable --json-input ('{ "name": "Bob" }' -replace '([\\]*)"', '$1$1\"') output.txt
Note:
The above replacement operation also handles escaped embedded "
characters correctly.
E.g., { "name": "Nat \"King\" Cole" }
becomes
{ \"name\": \"Nat \\\"King\\\" Cole\" }
, with the \
before "
properly escaped as \\
See this regex101.com page for an explanation of the regex and replacement operation (for technical reasons, the linked page uses C#'s string syntax, but the solution is equivalent to what is shown here).
If you know your JSON input not to contain them, you can simplify to -replace '"', '\"'