Search code examples
bashvbscriptcopybatch-fileparents

"cp --parents" in batch file/VBScript


How would you write this having only batch files and VBScript at your disposal in a Windows environment?

find -name '*.ext' -exec cp --parents {} destination/ \;

Or put it this way:

  • Look recursively in the current folder for some filename pattern (ending with an extension called ext in the example above),
  • Copy each of these files to a destination folder (wherever that is) preserving directory tree structure (or creating any missing intermediate directories) as in current folder.

Solution

  • This should work:

    for /r %%a in (*.cmd) do xcopy %%a C:\DESTINATION%%~pa
    

    Note that DESTINATION should never be a subdirectory of the directory you are trying to copy from, otherwise for /r goes into a recursive loop copying files it has already copied creating longer and longer directory paths (don't ask me how I know).

    You could make it slightly more robust using xcopy /c (to continue copying even if errors occur). You may also want to look at xcopy /? to see if there is anything else of value there (/q, /r, /o, etc).