Search code examples
batch-filemove

Move Multiple Files from Subfolders to Single Folder using Windows batch script


I have a requirement where the files are present in folders and the subfolders. The subfolders are dynamically created with current date and time. All the files should be moved to one destination folder without the subfolders.

Folder A:

1.txt
2.txt
Folder 20180907-1240-008
         3.txt
         4.txt
Folder 20180907-1128-001
         5.txt
         6.txt
Folder 20180906-0040-010
         7.txt
         8.txt

The destination folder should look like below

Folder B:

   1.txt
   2.txt
   3.txt
   4.txt
   5.txt
   6.txt
   7.txt
   8.txt

the below command works in command prompt

for /r %d in (*) do copy "%d" "F:\Tickets\Movement\390558-Harmony-LCOPYREC\B

My batch script looks like below

@echo off
cd /d "A"
for /r %%d in (*) do copy "%d" "F:\Tickets\B"

I have an error as below while executing in a batch script

\Tickets\B\*
The system cannot find the file specified.
        0 file(s) copied.

How do I make the script working


Solution

  • Almost right, no need to CD, just specify the parent path to folder after /r also ensure you double quote correctly and preferbly put a backslash at the end of a path to copy to:

    for /r "C:\path to folderA" %%d in (*) do copy "%%d" "F:\Tickets\Movement\390558-Harmony-LCOPYREC\B\"
    

    if you do not want to copy all files and just .txt for example, simply change your criteria to (*.txt)

    for /r "C:\path to folderA" %%d in (*.txt) do copy "%%d" "F:\Tickets\Movement\390558-Harmony-LCOPYREC\B\"
    

    Also, not sure which path you really want as destination, but you can do:

    @echo off
    set "dest=F:\Tickets\B\"
    set "source=C:\some dir\A"
    for /r "%source%" %%d in (*) do copy "%%d" "%dest%"
    

    Copy and paste above code is into the batch file.