[英]Recursively Copy Files with Batch Script Without Using Xcopy
I need to recursively copy a set of files using a batch (DOS) script, maintaining the original directory structure. 我需要使用批处理(DOS)脚本递归复制一组文件,并保持原始目录结构。 Sounds easy, right? 听起来很简单,对吧? Here are the complications: 这是并发症:
How do I get the copy command to save to a new directory with the same name/location as the old one? 如何获得copy命令以与旧名称/位置相同的名称/位置保存到新目录?
This is untested. 这是未经测试的。 The code supposedly duplicate the folder structure, but not copy files. 该代码应该复制文件夹结构,但不能复制文件。 If the test seems to be correct, remove the ECHO
part from the copy
command. 如果测试似乎正确,请从copy
命令中删除ECHO
部分。 The first parameter is "sourceDir" and the second one is "targetDir". 第一个参数是“ sourceDir”,第二个参数是“ targetDir”。
EDIT : Small detail fixed 编辑 :修复了小细节
@echo off
if not exist %2 md %2
set targetDir=%~F2
cd %1
call :processFolder
goto :EOF
:processFolder
setlocal EnableDelayedExpansion
rem For each folder in this level
for /D %%a in (*) do (
rem Enter into it, process it and go back to original
cd %%a
set "targetDir=%targetDir%\%%a"
if not exist "!targetDir!" md "!targetDir!"
ECHO copy *.* "!targetDir!"
call :processFolder
cd ..
)
@echo off
setlocal enableextensions disabledelayedexpansion
set "exitCode=0"
set "sourceDir=%~1"
set "targetDir=%~2"
if not defined sourceDir (
call :usage
goto endProcess
)
if not defined targetDir (
call :usage
goto endProcess
)
for %%f in ("%sourceDir%") do set "sourceDir=%%~ff"
for %%f in ("%targetDir%") do set "targetDir=%%~ff"
if not exist "%sourceDir%" (
call :error "Source directory does not exist"
goto endProcess
)
if /i "%sourceDir%"=="%targetDir%" (
call :error "Source and target are the same"
goto endProcess
)
ver > nul
call :recursiveFileCopy "%sourceDir%" "%targetDir%"
if errorlevel 1 set "exitCode=1"
goto endProcess
:recursiveFileCopy sourceDir targetDir
setlocal
set "sourceDir=%~f1"
set "targetDir=%~f2"
if not exist "%targetDir%\" md "%targetDir%" || call :error "Failed to create [%targetDir%]"
if not errorlevel 1 (
dir /a-d "%sourcedir%\*" >nul 2>nul && copy /y "%sourcedir%\*" "%targetdir%"
pushd "%sourcedir%"
for /d %%d in (*) do if not errorlevel 1 call :recursiveFileCopy "%%~fd" "%targetDir%\%%~nxd"
popd
)
endlocal
goto :eof
:usage
echo(
echo( Usage: %~n0 sourceDir targetDir
echo(
:error
echo(%~1
set "exitCode=1" & cmd /d /q /c exit /b 1
goto :eof
:endProcess
endlocal & exit /b %exitCode%
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.