Replacing Special Characters

by Dec 2, 2015

Sometimes it is crucial to replace special characters in text before you can use it. For example, if you plan to create Active Directory accounts, names cannot contain language-specific special characters.

Here is a universal function that can turn text into safe text:

#requires -Version 1

function ConvertTo-NeutralString ($Text)
{
  $changes = New-Object System.Collections.Hashtable
  $changes.ß = 'ss'
  $changes.Ä = 'Ae'
  $changes.ä = 'ae'
  $changes.Ü = 'Ue'
  $changes.ü = 'ue'
  $changes.Ö = 'Oe'
  $changes.ö = 'oe'
  $changes.' ' = '_'
  
  Foreach ($key in $changes.Keys)
  {
    $text = $text.Replace($key, $changes.$key)
  }

  $text
}

In its core, it uses a case-sensitive hash table to store the characters you are looking for, and the replacements you would want instead.

Run it like this:

 
PS> ConvertTo-NeutralString 'Mr Mößterler wants an "Österreichisches Steak".'
Mr_Moessterler_wants_an_"Oesterreichisches_Steak". 
 

Twitter This Tip! ReTweet this Tip!