我需要使用批处理(DOS)脚本递归复制一组文件,维护原始目录结构。听起来很简单吧?以下是复杂情况:
如何将copy命令保存到与旧目录具有相同名称/位置的新目录?
答案 0 :(得分:1)
这是未经测试的。该代码应该复制文件夹结构,但不复制文件。如果测试似乎正确,请从ECHO
命令中删除copy
部分。第一个参数是“sourceDir”,第二个参数是“targetDir”。
编辑:修复小细节
@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 ..
)
答案 1 :(得分:0)
@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%