I need to recursively copy a set of files using a batch (DOS) script, maintaining the original directory structure. 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?
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. The first parameter is "sourceDir" and the second one is "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%
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.