I am trying to replace a character to escape it in a Powershell string to convert it to JSON later. I would like to replace the double quotes " in the cmdline by a single quote followed by a double quotes, to escape the double quotes.
I have this string : user123" -a.exe
I would like to have user123'" -a.exe
I try different combinations with the -replace function like
$test -replace '"',''"'
but no one works due to the particularity of these characters.
Thanks in advance for your help
If you're dealing with a manipulating quoted text, and find the escaping rules are confusing and/or result in obfuscated code, you can also deal with it as here-strings. Within the here-string delimiters (@'-'@) normal quoting rules don't apply. It can make for longer code, but may be more intuitive to read and debug or do maintenance on later.
This is obviously a trivial example, but as the amount of quoted text and increases so will the advantage of using the here-strings over constructing arguments inline using escaped characters.
To force Windows PowerShell to interpret a double quotation mark literally, use a backtick(`) character.
To learn most of the variations and tricks to work with Quotes, type
at Powershell console.
You need to use backtick(`) character to escape special characters and use String.Replace method
Result: