Search code examples
powershellreplacerangespecial-characters

Replacing special character ranges in power shell


I am trying to do a test to replace special characters in my file. The replace string pattern contains the characters in ranges that i need to replace with ?

"Hello [char]0x00,[char]0x09,[char]0x0B,[char]0x1F,[char]0x7F,[char]0xFF" -replace  '[[char]0x00-[char]0x09[char]0x0B-[char]0x1F[char]0x7F-[char]0xFF]','?'

Hello [char]0x00,[char]0x09,[char]0x0B,[char]0x1F,[char]0x7F,[char]0xFF

Right now the above test command is not replacing anything

How can i test whether this works or not?

Can you help me in writing the command to replace all special characters in the following range?.

\x00-\x09
\x0B-\x1F
\x7F-\xFF


Solution

  • You need to use $() SubExpressions for your code to work. Like so:

    "Hello $([char]0x00),$([char]0x09),$([char]0x0B),$([char]0x1F),$([char]0x7F),$([char]0xFF)" -replace  "[$([char]0x00)-$([char]0x09)$([char]0x0B)-$([char]0x1F)$([char]0x7F)-$([char]0xFF)]","?"
    

    Output:

    Hello ?,?,?,?,?,?