PowerShell重命名脚本问题:序号被错误添加至文件扩展名后
修正后的PowerShell脚本
$folderPath = $filePath # 获取文件名包含"SF78"的文件 $files = Get-ChildItem -Path $folderPath -File | Where-Object { $_.BaseName -match 'SF78' } foreach ($file in $files) { # 拆分文件名与扩展名,替换基名中的"SF78"为"MEDICAL" $newBaseName = $file.BaseName -replace 'SF78', 'MEDICAL' $extension = $file.Extension $newName = "$newBaseName$extension" # 处理重名情况,在文件名(不含扩展名)后添加序号(1)(2)... $counter = 1 while (Test-Path (Join-Path -Path $folderPath -ChildPath $newName)) { $newName = "$newBaseName($counter)$extension" $counter++ } # 执行重命名并输出日志 $newPath = Join-Path -Path $folderPath -ChildPath $newName Rename-Item -Path $file.FullName -NewName $newName -ErrorAction Stop Write-Host "已重命名: $($file.Name) -> $newName" }
关键修正说明
- 拆分文件名与扩展名:使用
$file.BaseName(不含扩展名的纯文件名)和$file.Extension(文件扩展名)分别处理,从根源避免序号错误添加到扩展名后。 - 精准替换范围:仅对
BaseName执行替换操作,确保"SF78"的替换只作用于文件名部分,不影响扩展名。 - 重名逻辑优化:循环中直接在新基名后拼接
($counter)再追加扩展名,保证序号严格位于文件名和扩展名之间。 - 避免对象隐式转换:不再直接操作FileInfo对象,明确处理字符串形式的文件名片段,消除隐式转换导致的逻辑错误。
内容的提问来源于stack exchange,提问作者JeffR
相关产品推荐
相关产品推荐

