I'm trying to build a function in Powershell that I can use every time I have to replace a list of special characters with other characters. For example, this is the list of the special chars:
$Specialchars = '["ü","ä","ö","ß","æ","Œ","œ","°","~","Ø"]'
And I want that function to replace for example the "ü" with "ue" or the "Ø" with "o" and so on. The idea is to run the function against any string that I want to have those special characters replaced the way I want.
For now, I tried this:
function ReplaceSpecialChars($chars)
{
return $chars -replace "Ø","o"
return $chars -replace "~",""
return $chars -replace "œ","oe"
}
and it works only when it founds the first special characters, the "Ø" and not for example when I run it against a string which has the "~". I'm not an expert of Powershell function at all, so I was wondering if somebody has some hints to help me.
Thanks a lot !
You must assign the result of the replacement before doing the next.
Here is an updated version of the function, incl a way to define your replacements:
function ReplaceSpecialChars([string]$string) {
# define replacements:
@{
"ä" = "ae"
"ß" = "ss"
# ...
}.GetEnumerator() | foreach {
$string = $string.Replace($_.Key, $_.Value)
}
return $string
}
Note that you might want to define lowercase + uppercase replacements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With