如何在批量复制含子文件夹的文件时不覆盖并保留重复文件
结论
该需求可以实现。你原本使用的copy命令本身没有自动保留两份重名文件的参数,需要新增重名判断逻辑,自动为重复文件添加后缀后再复制即可,用Windows自带工具就能完成操作,无需额外安装软件。
实现方案
方案1:使用批处理脚本(适合所有Windows版本)
将以下代码保存为flat_copy.bat文件,修改好源路径和目标路径后双击运行即可:
@echo off setlocal enabledelayedexpansion :: 请修改下面两个路径为你的实际路径 set "source_dir=d:\source\A" set "dest_dir=d:\destination" :: 自动创建目标文件夹 if not exist "%dest_dir%" md "%dest_dir%" :: 递归遍历源目录下所有文件 for /r "%source_dir%" %%f in (*) do ( set "file_base=%%~nf" set "file_ext=%%~xf" set "target_path=%dest_dir%\!file_base!!file_ext!" set "suffix=1" :: 重名判断逻辑,存在同名文件则自动加序号 :check_exist if exist "!target_path!" ( set "target_path=%dest_dir%\!file_base!_!suffix!!file_ext!" set /a suffix+=1 goto check_exist ) :: 执行复制,不输出复制成功的冗余提示 copy "%%f" "!target_path!" >nul echo 完成复制:%%~nxf -> !target_path! ) echo 全部文件复制完成 pause endlocal
- 重名文件会自动添加
_1、_2格式的序号后缀,所有文件都会保留不会覆盖 - 运行后会输出每个文件的复制结果,你可以直观看到重名文件的重命名情况
方案2:使用PowerShell命令(适合Win10/Win11系统)
直接在PowerShell窗口执行以下命令即可,替换为你自己的路径:
Get-ChildItem -Path "D:\source\A" -File -Recurse | ForEach-Object { $suffix = 1 $newName = $_.Name $targetPath = "D:\destination\$newName" while(Test-Path $targetPath) { $newName = $_.BaseName + "_$suffix" + $_.Extension $targetPath = "D:\destination\$newName" $suffix++ } Copy-Item -Path $_.FullName -Destination $targetPath }
- 逻辑和批处理方案一致,自动为重名文件加序号后缀
- 不需要额外保存脚本,直接执行命令即可完成操作
内容的提问来源于stack exchange,提问作者HappyBeckmann
相关产品推荐
相关产品推荐

