loct
loct

Reputation: 367

Escaping special characters in a variable in PowerShell

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

Answers (1)

Simon B
Simon B

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

Related Questions