Search code examples
filebatch-filecopyrobocopy

ROBOCOPY - Copy folders content to a single folder


Here is some code I made :)

@echo off
set source="R:\Contracts\"
set destination="R:\Contracts\Sites\"
ROBOCOPY %source% %destination% *.srt *.pdf *.mp4 *.jpg /COPYALL /R:0 /S
for /r %source in (*) do @copy "%destination" .

R:\Contracts\ is full of folders which have files in them.

I want to copy all to R:\Contracts\Sites\ and flatten the folder structure.

Everything copies well but also the folder structure.

Thank you


Solution

  • No single command will flatten the hierarchy for you; you will have to use multiple commands. It can be done simply by using FOR /R to walk the hierarchy, coupled with your copy/move command of choice (move, copy, xcopy, robocopy). Because your destination is within the source hierarchy, you need an IF to prevent the destination from being a source.

    Before proceeding you should stop and think about what happens if the same file name appears in multiple source folders. You can only have one version in your destination folder. Can you guarantee no duplicate names exist? If not, which file should be kept? How can you structure the command to keep the file you want? This complication is probably why no command was ever written to simply flatten a hierarchy.

    Here is your ROBOCOPY command integrated with the FOR /R solution.

    @echo off
    set source="R:\Contracts"
    set destination="R:\Contracts\Sites"
    
    ::Not sure if this is needed
    ::It guarantees you have a canonical path (standard form)
    for %%F in (%destination%) do set destination="%%~fF"
    
    for /r %source% %%F in (.) do if "%%~fF" neq %destination% ROBOCOPY "%%F" %destination% *.srt *.pdf *.mp4 *.jpg /COPYALL /R:0