Search code examples
windowsbatch-filexcopyrobocopy

Copy directory and create upper directory structure


In windows (desktop, a batch file, xcopy, robocopy) is there a way to copy a directory and have the structure above it created on the destination?

For example, say I have a directory of files at c:\data\outlook\profiles\2013.

I want to copy the 2013 directory to c:\copy but want it to look like this: c:\copy\data\outlook\profiles\2013.

Of course, I can manually create the structure before the copy, but I am looking to do this in bulk.


Solution

  • Here is a routine that should copy the target with its full path.

    @echo off
    call :CopyWithPath "C:\Data\Outlook\Profiles\2013" "C:\Copy"
    exit /b %ErrorLevel%
    
    :CopyWithPath <Source> <Target>
    md "%~f2\%~p1" && copy "%~f1" "%~f2\%~p1"
    exit /b %ErrorLevel%
    

    Example of the command with values

    md "C:\Copy\Data\Outlook\Profiles\" && copy "C:\Data\Outlook\Profiles\2013" "C:\Copy\Data\Outlook\Profiles\"