Batch file to copy directories recursively

Batch FileCopy

Batch File Problem Overview


Is there a way to copy directories recursively inside a .bat file? Is an example of this available?

Batch File Solutions


Solution 1 - Batch File

Look into xcopy, which will recursively copy files and subdirectories.

There are examples, 2/3 down the page. Of particular use is:

> To copy all the files and subdirectories (including any empty subdirectories) from drive A to drive B, type: > > xcopy a: b: /s /e

Solution 2 - Batch File

After reading the accepted answer's comments, I tried the robocopy command, which worked for me (using the standard command prompt from Windows 7 64 bits SP 1):

robocopy source_dir dest_dir /s /e

Solution 3 - Batch File

You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:

@echo off
call :treeProcess
goto :eof

:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
copy *.* C:\dest\dir
for /D %%d in (*) do (
    cd %%d
    call :treeProcess
    cd ..
)
exit /b

https://stackoverflow.com/questions/8397674/windows-batch-file-looping-through-directories-to-process-files/8398621#8398621

Solution 4 - Batch File

I wanted to replicate Unix/Linux's cp -r as closely as possible. I came up with the following:

xcopy /e /k /h /i srcdir destdir

Flag explanation:

/e Copies directories and subdirectories, including empty ones.
/k Copies attributes. Normal Xcopy will reset read-only attributes.
/h Copies hidden and system files also.
/i If destination does not exist and copying more than one file, assume destination is a directory.


I made the following into a batch file (cpr.bat) so that I didn't have to remember the flags:

xcopy /e /k /h /i %*

Usage: cpr srcdir destdir


You might also want to use the following flags, but I didn't:
/q Quiet. Do not display file names while copying.
/b Copies the Symbolic Link itself versus the target of the link. (requires UAC admin)
/o Copies directory and file ACLs. (requires UAC admin)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsarsnakeView Question on Stackoverflow
Solution 1 - Batch Filelc.View Answer on Stackoverflow
Solution 2 - Batch FileAntônio MedeirosView Answer on Stackoverflow
Solution 3 - Batch FileAaciniView Answer on Stackoverflow
Solution 4 - Batch FileMike ClarkView Answer on Stackoverflow