我找到了如何在GetInvalidFileNameChars()
脚本中使用PowerShell方法。然而,它似乎也过滤掉了空白(这正是我不想要的)。
编辑:也许我的要求不够清楚。我希望下面的函数包含文件名中已经存在的空格。目前,脚本过滤掉了空格。
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())), '')}
发布于 2018-09-27 01:22:31
我目前最喜欢的方法是:
$Path.Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
这将所有无效字符替换为_
,并且与其他选项相比,它非常具有可读性,例如:
$Path -replace "[$([RegEx]::Escape([string][IO.Path]::GetInvalidFileNameChars()))]+","_"
发布于 2014-04-14 18:22:50
我怀疑这与非显示字符被强制用于regex操作(并以空格表示)有关。
看看这是否更有效:
([char[]]$name | where { [IO.Path]::GetinvalidFileNameChars() -notcontains $_ }) -join ''
这将做一个直接的字符比较,似乎更可靠(嵌入的空格没有删除)。
$name = 'abc*\ def.txt'
([char[]]$name | where { [IO.Path]::GetinvalidFileNameChars() -notcontains $_ }) -join ''
abc def.txt
编辑-我相信@Ansgar关于将字符数组转换为string所导致的空格是正确的。这个空间是由$OFS引进的。
发布于 2016-05-06 03:53:02
我想用空格来替换所有的非法字符,这样空间就会被空间所取代。
$Filename = $ADUser.SamAccountName
[IO.Path]::GetinvalidFileNameChars() | ForEach-Object {$Filename = $Filename.Replace($_," ")}
$Filename = "folder\" + $Filename.trim() + ".txt"
https://stackoverflow.com/questions/23066783
复制相似问题