Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 549
loct Avatar asked Oct 29 '25 13:10

loct


1 Answers

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
like image 73
Simon B Avatar answered Nov 01 '25 08:11

Simon B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!