Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment