I was able to find how to use the GetInvalidFileNameChars()
method in a PowerShell script. However, it seems to also filter out whitespace (which is what I DON'T want).
EDIT: Maybe I'm not asking this clearly enough. I want the below function to INCLUDE the spaces that already existing in filenames. Currently, the script filters out spaces.
Function Remove-InvalidFileNameChars {
param([Parameter(Mandatory=$true,
Position=0,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[String]$Name
)
return [RegEx]::Replace($Name, "[{0}]" -f ([RegEx]::Escape([String][System.IO.Path]::GetInvalidFileNameChars())), '')}
Please try this one-liner with the same underlying function.
to match
to replace
My current favourite way to accomplish this is:
This replaces all invalid characters with
_
and is very human readable.I suspect it has to do with non-display characters being coerced to [string] for the regex operation (and ending up expressed as spaces).
See if this doesn't work better:
That will do a straight char comparison, and seems to be more reliable (embedded spaces are not removed).
Edit - I believe @Ansgar is correct about the space being caused by casting the character array to string. The space is being introduced by $OFS.
[System.IO.Path]::GetInvalidFileNameChars()
returns an array of invalid chars. If it is returning the space character for you (which it does not do for me), you could always iterate over the array and remove it.Then you can use
$chars
as you would have used the output fromGetInvalidFileNameChars()
.Casting the character array to
System.String
actually seems to join the array elements with spaces, meaning thatdoes the same as
when you actually want
As @mjolinor mentioned (+1), this is caused by the output field separator (
$OFS
).Evidence:
Change your function to something like this:
and it should do what you want.
I wanted spaces to replace all the illegal characters so space is replaced with space