Search code examples
recursionbatch-filexcopy

Copy Files recursively from inside directory to outside using batch file


There is this directory structure:

Dir1
--Dir2
    --File1
    --File2
--Dir3
    --File3
--File4
--File5

Now I want to copy all the files in subdirectory (Dir2, Dir3) to parent Directory Dir1 using batch files. I have come up with the below code but it doesn't work perfectly. I get the below output -

Directory2             --It has 4 files all together
Invalid number of parameters
Invalid number of parameters
Does E:\Directory1\Copy\File1.dat specify a file name   -- And only this file gets copied
or directory name on the target
(F = file, D = directory)?

Code -

@echo off
call :treeProcess
Pause
goto :eof

:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
for /D %%d in (*) do (
    echo %%d
    cd %%d
    for %%f in (*) do xcopy %%f E:\Movies\Copy\%%f
    call :treeProcess
    cd ..
)
exit /b

Solution

  • No need for a batch file. Execute the following command from your Dir1 folder:

    for /r /d %F in (*) do @copy /y "%F\*"
    

    As a batch file

    @echo off
    for /r /d %%F in (*) do copy /y "%%F\*"
    

    BUT - Be aware that you may have the same file name in multiple child folders. Only one will survive in your Dir1.

    EDIT

    The above assumes you are running the command, (or the script) from the Dir1 folder. It can be run from anywhere if the script is augmented to include the path to Dir1.

    for /r "pathToDir1" /d %F in (*) do @copy /y "pathToDir1\%F\*"
    

    or as a batch file

    @echo off
    set "root=pathToDir1"
    for /r "%root%" /d %%F in (*) do copy /y "%root%\%%F\*"
    

    You could pass the path to Dir1 as an argument to the batch file. Pass in . as the path if you want to use the current folder.

    @echo off
    for /r %1 /d %%F in (*) do copy /y "%~1\%%F\*"