如何用PowerShell批量重命名海量含共同中间因子的文件并去重?
批量重命名并去重的PowerShell解决方案
核心重命名逻辑
你的文件名规律是任意前缀字符串 + _ytd. + 目标文件名,完全不需要手动指定每一种前缀,用正则表达式匹配替换即可。用Get-ChildItem(比Dir更规范)结合正则的核心命令如下:
Get-ChildItem -File -Filter "*_ytd.*.dds" | Rename-Item -NewName { $_.Name -replace '^.*_ytd\.', '' } -WhatIf
-File:仅处理文件,排除目录,提升处理效率-Filter:提前过滤符合格式的文件,减少后续运算量-replace '^.*_ytd\.', '':正则匹配从文件名开头到_ytd.的所有内容并替换为空(^表示开头,\.是对文件名中点的转义)-WhatIf:先预览重命名结果,确认逻辑正确后再移除该参数执行实际操作
重复文件处理方案
针对40万文件的规模,必然会产生大量同名目标文件,提供两种处理思路:
方案1:保留最新版本,删除重复文件
先按目标文件名分组,每组仅保留最后修改时间最新的文件,删除其余重复项:
# 按目标文件名分组,保留每组最新文件,删除其他重复文件 Get-ChildItem -File -Filter "*_ytd.*.dds" | Group-Object -Property { $_.Name -replace '^.*_ytd\.', '' } | ForEach-Object { if ($_.Count -eq 1) { return } $latestFile = $_.Group | Sort-Object LastWriteTime -Descending | Select-Object -First 1 $_.Group | Where-Object { $_ -ne $latestFile } | Remove-Item -Force -WhatIf } # 执行最终重命名 Get-ChildItem -File -Filter "*_ytd.*.dds" | Rename-Item -NewName { $_.Name -replace '^.*_ytd\.', '' } -WhatIf
方案2:自动给重复文件加序号
如果不想删除文件,可给重复文件添加序号后缀(如test_1.dds、test_2.dds):
Get-ChildItem -File -Filter "*_ytd.*.dds" | ForEach-Object { $targetName = $_.Name -replace '^.*_ytd\.', '' $targetPath = Join-Path $_.DirectoryName $targetName $counter = 1 # 若目标文件已存在,生成带序号的新名称 while (Test-Path $targetPath) { $fileName = [System.IO.Path]::GetFileNameWithoutExtension($targetName) $extension = [System.IO.Path]::GetExtension($targetName) $targetName = "$fileName`_$counter$extension" $targetPath = Join-Path $_.DirectoryName $targetName $counter++ } $_ | Rename-Item -NewName $targetName -WhatIf }
大规模处理性能优化
针对40万文件的量级,可通过以下方式提升处理速度:
- 优先将文件复制到本地磁盘操作,避免在网络共享目录执行
- 关闭PowerShell进度条:
$ProgressPreference = 'SilentlyContinue' - 分批次处理,避免一次性加载过多文件:
Get-ChildItem -File -Filter "*_ytd.*.dds" | ReadCount 1000 | ForEach-Object { $_ | Rename-Item -NewName { $_.Name -replace '^.*_ytd\.', '' } -WhatIf }
内容的提问来源于stack exchange,提问作者tmntcool
相关产品推荐
相关产品推荐

