Tree-To-Flat Copy Using XCopy

on Tuesday, December 16, 2008

If you have a tree folder as follows:


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


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


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

Jahid Hasan said...

GSCopy Pro v6.0 (RoboCopy Alternative) with Open File Agent
GSCopyPro is a single command-line tool (CLI) that can copy, replicate and move files from one folder to another. This folder can be on the same machine/ server or another server elsewhere. What makes GSCopyPro stand out from other competitors is the fact it works on 32-bit as well as 64-bit systems and has no restrictions. It can easily be scheduled to run as a scheduled task and fully automated. GSCopyPro also comes with an open file agent which can copy files that are locked/ opened by other processes. This feature is supported in all windows versions from widows XP/ 2003 and later.
Go To:>>