Search code examples
windowsbatch-filescriptingxcopy

How to replicate a directory structure using xcopy in windows


I have a text file containing a list of folders.My text file looks like this:

"D:\old\FOLDER1"  
"D:\old\FOLDER2"  
"D:\old\FOLDER3"  
"D:\old\FOLDER4"  
"D:\old\FOLDER5"  

all these folders have subfolders and files under it

what I want to do is use xcopy to copy FOLDER1, FOLDER2 , FOLDER3 FOLDER4 and FOLDER5 replicate folders ,replicating the structure of those folders so in output , I want to get

D:\output\bkup\FOLDER1\............Including all subfolders and files D:\output\bkup\FOLDER2\............Including all subfolders and files D:\output\bkup\FOLDER3\.......... Including all subfolders and files 
D:\output\bkup\FOLDER4\............Including all subfolders and files 
D:\output\bkup\FOLDER5\............ Including all subfolders and files 

I have written below script which works fine for one folder

set sourceFolder="D:\old\FOLDER5"
set destinationFolder=%sourceFolder:~7,-1%
echo %destinationFolder%
xcopy /s /e /i /h /r /y %sourceFolder%  "D:\output\bkup%destinationFolder%"

but since # of directories to copy is 100+ ,I like to use a for loop or pass the list of directories to copy in a text file , that's what I don't know how to handle it.

please help me ,I'm not expert in batch file writing.


Solution

  • You can use for /f to read (parse if needed) a textfile line by line. Use "delims=" to read the line as a whole. Don't forget to add quotes to prevent having multiple arguments and strip the quotes in the subprocedure

    for /f "delims=" %%a in (yourtextfile.txt) do call :docopy "%%a"
    goto :eof
    
    :docopy
    set sourceFolder=%~1
    set destinationFolder=%sourceFolder:~7,-1%
    echo %destinationFolder%
    xcopy /s /e /i /h /r /y %sourceFolder%  "D:\output\bkup%destinationFolder%" 
    goto :eof