我有一个包含一堆子目录的目录,以及这些子目录下面的文件(我正在运行Windows 10):
C:\MyFolder\Able
C:\MyFolder\Able\Alpha
C:\MyFolder\Able\Manifest
C:\MyFolder\Baker
C:\MyFolder\Baker\Bravo
C:\MyFolder\Baker\Manifest
C:\MyFolder\Charlie
C:\MyFolder\Charlie\Charlie
C:\MyFolder\Charlie\Manifest
C:\MyFolder\Dog
C:\MyFolder\Dog\Delta
C:\MyFolder\Dog\Manifest
我想创建一个批处理文件,将C:\MyFolder
的所有子目录复制到一个特定的文件夹中,保留目录结构并覆盖所有重复的文件,但要删除C:\MyFolder
下的第一级子目录像这样:
C:\MyFolder\Able\*.* --> C:\NewFolder\*.*
C:\MyFolder\Able\Alpha --> C:\NewFolder\Alpha\*.*
C:\MyFolder\Able\Manifest --> C:\NewFolder\Manifest\*.*
C:\MyFolder\Baker --> C:\NewFolder\*.*
C:\MyFolder\Baker\Bravo --> C:\NewFolder\Bravo\*.*
C:\MyFolder\Baker\Manifest --> C:\NewFolder\Manifest\*.*
C:\MyFolder\Charlie --> C:\NewFolder\*.*
C:\MyFolder\Charlie\Charlie --> C:\NewFolder\Charlie\*.*
C:\MyFolder\Charlie\Manifest --> C:\NewFolder\Manifest\*.*
C:\MyFolder\Dog --> C:\NewFolder\*.*
C:\MyFolder\Dog\Delta --> C:\NewFolder\Delta\*.*
C:\MyFolder\Dog\Manifest --> C:\NewFolder\Manifest\*.*
我最初的想法是使用命令"dir /b /s /a:d C:\MyFolder"
获取所有子文件夹名称,然后使用xcopy
命令获取每行并复制文件,但我不能似乎建立了联系。
提前致谢:)
答案 0 :(得分:1)
这应该有效:
@ECHO OFF
SETLOCAL EnableDelayedExpansion
REM **************************************************
SET source_dir=C:\MyFolder
SET target_dir=C:\NewFolder
REM **************************************************
FOR /F "delims=" %%G IN ('DIR /S /B /A:D "%source_dir%"') DO (
SET "folder_name=%%G"
CALL :copy
)
ECHO. & ECHO. & ECHO. & ECHO. & ECHO. & ECHO Done^^!
PAUSE
EXIT
:copy
SET "target_folder_name=!folder_name:%source_dir%\=!"
ECHO !target_folder_name! | FINDSTR /C:"\\" >nul && SET "target_folder_name=!target_folder_name:*\=!" || SET "target_folder_name=."
ROBOCOPY "!folder_name!" "%target_dir%\!target_folder_name!" /IT
EXIT /B
这基本上会删除每个文件夹路径中的C:\MyFolder\*\
,其余的名称,路径或.
(如果它是C:\MyFolder
的直接子文件夹)被添加到target_dir
路径。
如果路径仍然存在,您还可以将此路径缩小为仅名称,并将所有子目录的所有文件合并到一个子文件夹中。
为此,只需将:copy
位替换为:
:copy
SET "target_folder_name=!folder_name:%source_dir%\=!"
ECHO !target_folder_name! | FINDSTR /C:"\\" >nul || SET "target_folder_name=."
SET "loop_counter=0"
:loop
SET /A "loop_counter=%loop_counter%+1"
IF %loop_counter%==10 (ECHO Error: Could not copy !folder_name! && EXIT /B)
ECHO !target_folder_name! | FINDSTR /C:"\\" >nul && SET "target_folder_name=!target_folder_name:*\=!" && SET /A "counter=%counter%+1" && GOTO loop
ROBOCOPY "!folder_name!" "%target_dir%\!target_folder_name!" /IT
EXIT /B
这会添加一个循环以删除最多10个父目录(如果有)和loop_counter以防止无限循环。显然,只需调整10
IF-Statement
中的IF %loop_counter%==10
即可获得更多循环。