Attempt To Use Batch Files While Keep Structure
I wanted to use robocopy
, but it is not possible due to my text file has filenames attached.
I ended up have to use copy
instead.
I wanted to copy files like this…
Source: S:folderABCDEproduct_pdfDriveDriveDeluxeAluminumBathChair_RTL12202KDR.pdf Destination: C:wamp64FGproduct_pdfDriveDriveDeluxeAluminumBathChair_RTL12202KDR.pdf
Here is how my text file (ActivePDF.txt) listed..
product_pdfDriveDriveDeluxeAluminumBathChair_RTL12202KDR.pdf product_pdfDriveDriveCommodesNRS185007-11117N.pdf product_pdfDriveDriveCommodes11125Series.pdf product_pdfDriveDriveSuctionCupGrabBar_RTL13082.pdf product_pdfDriveDriveChromeKnurledGrabBar.pdf
My attempted batch file is looked like this
@echo on enableextensions set main_folder=S:folderABCDE set my_folder=C:wamp64FG set log_file="%main_folder%CopyLog.txt" for /f "delims=" %%a in (ActivePDF.txt) do if exist "%main_folder%%%a" ( md "%my_folder%%%a" 2>nul copy /v /y "%main_folder%%%a" "%my_folder%%%a" )
It did copied, but it ended up created folder with “.pdf” and actual PDF files are inside that “.pdf” folders. (Therefore, each PDF contained in the own folder…)
I think I’m getting there… but I do wonder if there is any cleaner way to do it.
Answer
It’s the commands in the for
loop that are causing the problem: %%a
contains both the subdirectory path and the PDF file name, so md "%my_folder%%%a" 2>nul
will create in the target folder a directory path which includes the PDF name as the last subdirectory.
When the target path is a directory the copy
command copies the source file(s) into it, with the result you observed.
While it is possible to parse %%a
to extract the directory path and file names, there is a trick that can be used to reference the directory path without parsing: if %%a
contains a file name with directory path, then %%a..
will reference the directory path. Even though %%a
is a file path, the parsing of %%a..
will identify the containing directory without checking whether the last element of %%a
is a file or directory.
So the commands in the for
loop become:-
md "%my_folder%%%a.." 2>nul copy /v /y "%main_folder%%%a" "%my_folder%%%a.."
The md
is needed to create the target subdirectory if it does not exist.