Is there a way to copy directories recursively inside a .bat file? If so, an example would be great. thanks.
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)
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
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
Windows Batch File Looping Through Directories to Process Files?
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