2014-01-09 39 views
1

我需要使用批處理(DOS)腳本遞歸複製一組文件,並保持原始目錄結構。聽起來很簡單,對吧?以下是併發症:使用批處理腳本遞歸複製文件而不使用Xcopy

  1. xcopy在服務器上不可用我將使用批處理腳本。因此,我必須使用複製命令。
  2. 一個徹底的互聯網搜索這個主題只會導致使用xcopy或腳本的一些專門用途(這只是一個通用的複製/粘貼作業)。
  3. 我從90年代起就沒有在DOS下編寫過。

如何獲取複製命令以保存到與舊的名稱/位置相同的新目錄?

+0

* ROBOCOPY *附帶某些版本的Windows,猶如類固醇XCOPY。 –

+2

你使用的是哪個版本的Windows沒有XCOPY?我認爲所有版本的Windows都有XCOPY。你確定你的PATH設置正確,以包含外部命令所在的系統文件夾嗎? – dbenham

+0

服務器2008年,但它已被剝離並可能配置錯誤。另一個挑戰堆積在我已經滿盤子上! – user3178452

回答

1

這是未經測試的。代碼應該複製文件夾結構,但不復制文件。如果測試看起來是正確的,請從copy命令中刪除ECHO部件。第一個參數是「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 .. 
) 
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%