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 almost 2 years

    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 almost 6 years
    The variable contents contain special characters. Not the variable name itself.
  • EagleDev
    EagleDev over 5 years
    what if I need not to escape $DestFileZip? E.g $DestFileZip = "my-value" and the content print my-value