Escaping special characters in a variable in PowerShell

14,824

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
Share:
14,824
loct
Author by

loct

Updated on June 05, 2022

Comments

  • loct
    loct 4 months

    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?

  • Maximilian Burszley
    Maximilian Burszley about 4 years
    The variable contents contain special characters. Not the variable name itself.
  • EagleDev
    EagleDev almost 4 years
    what if I need not to escape $DestFileZip? E.g $DestFileZip = "my-value" and the content print my-value