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
To force Windows PowerShell to interpret a double quotation mark literally, use a backtick(`) character.
PS C:\> $test = "user123`" -a.exe"
PS C:\> $test
user123" -a.exe
PS C:\> $test = $test -replace "`"","'`""
PS C:\> $test
user123'" -a.exe
To learn most of the variations and tricks to work with Quotes, type
Help about_Quoting_Rules
at Powershell console.
You need to use backtick(`) character to escape special characters and use String.Replace method
$test = "user123`" -a.exe"
$test.replace("`"","`'`"")
Result:
user123'" -a.exe
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.
$string = @'
user123" -a.exe
'@
$match = @'
"
'@
$replace = @'
"'
'@
$string.replace($match,$replace)
user123"' -a.exe
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.