我有大量資料包含不支持字符的檔案名,因為我想將這些檔案移動到不同的位置,如果不重命名這些檔案是不可能的。運行我的代碼時,他給出錯誤,說他找不到他想要重命名的檔案,提前感謝您的任何幫助。
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\"
uj5u.com熱心網友回復:
我做了一些調整, $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\"
uj5u.com熱心網友回復:
.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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/358614.html
標籤:电源外壳
