Powershell: Removing Special Characters from Strings

You may or may not have seen my previous post about converting first characters to upercase Link.

Well, we can expand on this by using a function to capture symbols and auto uppercasing characters making it much easier when obtaining a unique and compatible UserPrincipalName or Alias for example.


If using an InfoPath form with SharePoint or any other type of form which may not support locking input boxes to certain characters, you end up relying on the person submitting to ensure the data being imputed it correct.

Now, the example which I am using the form submits the data to an SQL database which we pull the first and last name of the user to create into an orchestrator runbook.

So… nothing original, we’ll use Joe Bloggs-doe and capture grammatical mistakes and unsupported characters.

To do this I created the below function which removes all characters I specify in $specChars and sends them to a regex. I then use the get-culture command to convert the casing in the correct format then use a simple -replace on the result to remove the characters not required.


Function Convert-ToFriendlyName

{param ($Text)

# Unwanted characters (includes spaces and '-') converted to a regex:

$SpecChars = '!', '"', '£', '$', '%', '&', '^', '*', '(', ')', '@', '=', '+', '¬', '`', '', '<', '>', '.', '?', '/', ':', ';', '#', '~', "'", '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', ' '

$remspecchars = [string]::join('|', ($SpecChars | % {[regex]::escape($_)}))

# Convert the text given to correct naming format (Uppercase)

$name = (Get-Culture).textinfo.totitlecase(“$Text”.tolower())

# Remove unwanted characters

$name = $name -replace $remspecchars, ""

$name

}

$firstname = Convert-ToFriendlyName "joe !3432"$firstname
$lastname = Convert-ToFriendlyName "bloggs-doe!3432"$lastname

0 thoughts on “Powershell: Removing Special Characters from Strings”

Leave a Reply

Your email address will not be published. Required fields are marked *