I want to write a small utility function that replaces any sequence of forbidden chars in filename by a dash
For example :
foo.txt==>foo.txtSome string \o/==>Some string -o-https://stackoverflow.com/questions==>https-stackoverflow.com-questions
I write the function like this:
function Get-SafeFileName{
param(
[Parameter(Mandatory, Position=0, ValueFromPipeline)]
[object]$Data
)
process {
$pattern = "[" + [regex]::Escape([string][System.IO.Path]::GetInvalidFileNameChars()) +"]+"
[regex]::Replace($Data, $pattern, "-")
}
}
This is working, except the space character is replaced even it's an allowed character.
This is a string results in This-is-a-string which isn't necessary.
How to fix that?
Digging a bit shows that [System.IO.Path]::GetInvalidFileNameChars() doesn't contains the space char (ascii code 32). But there are many other "space" alike chars.
Maybe the regex engine doesn't see the difference?