This little function lets you remove characters from a string. The twist is that it takes a character array, and will remove all characters in it from the input string.

This can come in handy if you need to for instance remove all special characters from a string. Please note that I have added a selection of special characters as default value for the Remove parameter.

If you take it for a spin, I’d love to hear your comments about it.

function Remove-Characters {
Remove characters from a string.
This function will take an array of characters, and will remove
those characters from the input string.
$myString | Remove-Characters
This will remove all 'default' characters from myString.
Remove-Characters -InputString $myString -Remove ([char[]](0..47 + 58..64 + 91..96 + 123..255 | ForEach-Object {[char]$_}))
This will remove all characters in the ASCII table except letters and numbers.
Remove-Characters -InputString $myString -Remove ([char[]](0..47 + 58..64 + 91..96 + 123..[int][char]::MaxValue | ForEach-Object {[char]$_}))
This will remove all special characters with the exception of letters and numbers. NOTE This one is a bit slower than the other two examples.
This code was translated and adapted from this StackOverflow answer:
Author: Øyvind Kallstad
Date: 11.02.2016
Version: 1.0
param (
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
[string] $InputString,
# Characters to remove. Default value is '!"#¤%&€/()=?`+[]{}@£$\¨^~*-_.:,;<> '
[Parameter(Position = 1)]
[char[]] $Remove = '!"#¤%&€/()=?`+[]{}@£$\¨^~*-_.:,;<> '
[char[]]$buffer = New-Object TypeName System.Char[] ArgumentList $InputString.Length
$index = 0
foreach ($character in $InputString.ToCharArray()) {
if (-not ($Remove -contains $character)) {
$buffer[$index] = $character
Write-Output (New-Object TypeName System.String ArgumentList ($buffer,0,$index))


  1. Hi Øyvind,

    Maybe I’m missing the point, but couldn’t you rather use something like the below instead?:

    [char[]]$Remove = ‘!”#¤%&€/()=?`+[]{}@£$\¨^~*-_.:,;’
    $inputstring = ‘test!”#¤%&€/()##=?`+[]test{}@£$\¨^~*+*-_.:,;test’
    $InputString -replace “$([regex]::Escape($Remove).Replace(‘\ ‘,’|’))”, ”


    1. Hi Dirk. Thanks for your comment. You most certainly could. That’s the beauty of it isn’t it? Many ways to Rome and all that 🙂 The reason I didn’t use regex was just performance really. I have read that using regex will take quite a bit longer, but you will hardly notice it unless you try it on a really large string.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s