Reputation: 367
I have a variable in PowerShell that contains special characters like "<",">" and double quotes. Currently I am using something like -replace ">" , "^>"
,
-replace "<" , "^<"
, -replace '"' , "'"
. Is there a way to escape all special characters in this variable?
Upvotes: 4
Views: 23831
Reputation: 218
Wrap the variable in curly brackets, i.e.,
${<My-Variable>with<Special-Characters>} ="<test>"
${<My-Variable>with<Special-Characters>}
Returns
<test>
The below is taken from another post on Stack Overflow, but I can’t find the link.
If it is the variable that contains special characters, this should work. Within the @" "@
delimiters, variables and sub-expressions will get expanded, but quotes and other special characters are treated as literals.
$SpecialCharacters = @'
& "C:\Program Files\7-Zip\7z.exe" u -mx5 -tzip -r "$DestFileZip" "$DestFile"
'@
$SpecialCharacters
Upvotes: 6