How to strip illegal characters before trying to save filenames?

前端 未结 6 848
夕颜
夕颜 2020-12-08 20:04

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

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 20:40

    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:

    ([char[]]$name | where { [IO.Path]::GetinvalidFileNameChars() -notcontains $_ }) -join ''
    

    That will do a straight char comparison, and seems to be more reliable (embedded spaces are not removed).

    $name = 'abc*\ def.txt'
    ([char[]]$name | where { [IO.Path]::GetinvalidFileNameChars() -notcontains $_ }) -join ''
    
    abc def.txt
    

    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.

提交回复
热议问题