Tree-To-Flat Copy Using XCopy

on Tuesday, December 16, 2008

If you have a tree folder as follows:

%BRANCHPATH%\UserControls
%BRANCHPATH%\UserControls\ChangePassword\
%BRANCHPATH%\UserControls\MyProfile\
%BRANCHPATH%\UserControls\RegistrationWizard\


and you try to do a XCOPY as follows using the recursive option (/S), it copies entire folder structure into the target hive.

XCOPY %BRANCHPATH%\*.ascx "%HIVE%" /Y /R /S

However, if we just want to drop the files individually the above doesn’t work. The above will copy entire folders that contain the ascx files in the HIVE. This will cause problems. There is no way to do a tree-to-flat copy using any XCopy option.

One easy but cumbersome way to avoid this is to use full paths to each folder as follows:

XCOPY %BRANCHPATH%\UserControls\*.ascx "%HIVE%" /Y /R
XCOPY %BRANCHPATH%\UserControls\ChangePassword\*.ascx "%HIVE%" /Y /R
XCOPY %BRANCHPATH%\UserControls\MyProfile\*.ascx "%HIVE%" /Y /R
XCOPY %BRANCHPATH%\UserControls\RegistrationWizard\*.ascx "%HIVE%" /Y /R


The above will work, but you will have to specify each folder, and there may be a folder you end up missing. However, the following snippet is generic enough in that it will first create a list of all the folders and subfolders, create a temporary list of folders in a text file, go through each folder, grab the .ascx files in each folder and copy it to the HIVE. At the end delete the temporary text file:

dir %BRANCHPATH%\UserControls /A:D /B /S > tempListOfDirs.txt
For /F %%A IN (tempListOfDirs.txt) Do (
If Exist %%A* (
XCOPY %%A\*.ascx "%HIVE%" /Y /R
)
)
del tempListOfDirs.txt

2 comments:

Anonymous said...

BRILLIANT! I wanted to copy all JPG files from an SD card inserted in a card reader into one folder, extracting them from the DCIM folder structure. Your solution, suitably modified, worked a treat. Thanks very much!

Anonymous said...

This is a great sample, but note it will not work if your dir paths contains spaces.

The For /F structure considers spaces as delimiters by default, so the updated sample below overrides the default delimiter and adds the double quotes around the path in the xcopy arg.

Here's the updated sample, hope it saves someone some time...again many thanks to the host for providing the original--

dir %BRANCHPATH%\UserControls /A:D /B /S > tempListOfDirs.txt
For /F "tokens=*" %%A IN (tempListOfDirs.txt) Do (
If Exist %%A* (
XCOPY "%%A\*.ascx" "%HIVE%" /Y /R
)
)
del tempListOfDirs.txt