不支持的字符



我有大量数据的文件名中包含不支持的字符,因为我想将这些文件移动到不同的位置,如果不重命名这些文件,这是不可能的。当运行我的代码时,他给出了一个错误,他有点找不到他想重命名的文档提前感谢您的帮助。

function AdjustFilename {
param (
[String]$Path
)
if ($Path.Chars($Path.Length - 1) -ne '') { $Path = $Path + '' }

$filelist = get-ChildItem  -LiteralPath $path -Recurse -File
foreach ($filename in $filelist) {

[String]$newfilename = $filename
$newfilename = $newfilename.Replace('?', '').Replace('/', '').Replace('', '').Replace('{', '').Replace('}', '').Replace('<', '').Replace('>', '').Replace('|', '').Replace(':', '').Replace('*', '')
$fullpath =  $filename.Fullname
if ("$filename" -ne "$newfilename") {
rename-item -LiteralPath $fullpath -NewName $newfilename
}
}
$pathlist = get-ChildItem -LiteralPath $path -Recurse -Directory
foreach ($subpath in $pathlist) {
AdjustFilename "$($Path)$($subpath)"
}

}
AdjustFilename "C:Temp"

.NET有一个非常方便的方法,可以返回所有无效的文件名字符。您可以使用它来创建一个正则表达式字符串,以将它们全部替换为空:

function Remove-InvalidFilenameCharacters {
param (
[String]$Path
)
# create a regex to replace the invalid filename characters
$invalidChars = '[{0}]' -f [RegEx]::Escape([System.IO.Path]::GetInvalidFileNameChars())
$filelist = Get-ChildItem  -LiteralPath $Path -Recurse -File
foreach ($file in $filelist) {
# remove all invalid characters from the file name
$newfilename = $file.Name -replace $invalidChars
# you don't have to test if the newname is different, because if this
# is the case, Rename-Item doesn't do anything to that file (No-Op)
$file | Rename-Item -NewName $newfilename
}
}
Remove-InvalidFilenameCharacters "C:Temp"

我做了一些调整,$filename是一个对象。既然你已经使用了-Recurse,你就不需要底部,因为它会使事情加倍。

function AdjustFilename {
param (
[String]$Path
)
if ($Path.Chars($Path.Length - 1) -ne '') { $Path = $Path + '' }

$filelist = get-ChildItem  -LiteralPath $path -Recurse -File
foreach ($filename in $filelist) {

[String]$newfilename = $filename.Name
$newfilename = $newfilename.Replace('?', '').Replace('/', '').Replace('', '').Replace('{', '').Replace('}', '').Replace('<', '').Replace('>', '').Replace('|', '').Replace(':', '').Replace('*', '')
$fullpath =  $filename.Fullname
if ("$filename" -ne "$newfilename") {
rename-item -LiteralPath $fullpath -NewName $newfilename
}
}
}
AdjustFilename "C:Temp"

最新更新