1

Replace Special Characters with PowerShell

I have been swamped with project work and webinars, so I haven’t been able to put a ton of time into finalizing new posts.  I have a lot of thoughts and new topics started.  So, expect some new Groovy examples and possibly some Essbase Cloud content.

Unti9l then, I came across this really nice little tidbit when trying to replace special characters in a file and thought those of you who are using PowerShell would benefit by having it.  The beauty of this is that you don’t need to know which characters need escaped.  For those of you like me that aren’t well versed in this topic, not having to know which characters need escaped to work will speed up the development of similar functions.

The following snippet is a simple function that accepts 3 parameters.

  1. The string to be searched with the characters to replace
  2. The string that will replace the characters
  3. The string of characters that need replaced

This function has defaults.  the first is required, but the second and third are not.  If the second and third parameters are now supplied, the defaults – #, ?, (, ), [, ], {, and }  – will be replaced with a blank string, effectively removing them.  These parameters can be passed, and the defaults will be ignored.

function Replace-SpecialChars {
  param(
    [string]$InputString,
    [string]$Replacement = "",
    [string]$SpecialChars = "#?()[]{}"
  )

  $rePattern = ($SpecialChars.ToCharArray() |ForEach-Object { [regex]::Escape($_) }) -join "|"
  $InputString -replace $rePattern,$Replacement
}

Replace-SpecialChars (Get-Content c:\test\replace.txt) | Set-Content c:\test\replaceNEW.txt

The above will create a new file named replaceNEW.txt with the contents of replace.txt, but will exclude the characters supplied to the function.

If this doesn’t make sense, take a look at this.  Let’s say we want to replace every x with xray.  The following command would accomplish this.

Replace-SpecialChars (Get-Content c:\test\replace.txt) "x" "xray" | Set-Content c:\test\replaceNEW.txt

So, this isn’t just for special characters!

If you have a cool script, share it by commenting!