how to use bat file to move files from subdirectories to one folder

1.3k views Asked by At

I'm trying to use a .bat file to go into a folder, and take all photos within it and its subfolders, and place them all into another directory. I know how to copy the folder exactly, with all subfolders remaining in place when copied with

@ECHO OFF
XCOPY E:\FromFolderNameX C:\toFolderNameY /m /y

but I only want all of the photos to be in one folder in the end, no subfolders. Can this be done with a batch file?

1

There are 1 answers

2
AlexP On BEST ANSWER
  • I am assuming that you want to copy (not move) the photos from the subtree starting at E:\FromFolderNameX into the directory C:\toFolderNameY.

  • I am assuming that by "photos" you mean .jpg files.

  • The one-line interactive command is

    for /r E:\FromFolderNameX %p in (*.jpg) do copy /y "%~p" C:\ToFolderNameY
    
  • If instead of JPG files you want to copy all files, just replace *.jpg with *.

  • If instead of an interactive one liner you want a batch file, the core of the batch file would be

    for /r "%~1" %%p in (*.jpg) do copy "%%~p" "%~2"
    

(%1 is the first positional argument = the top of the subtree from where you want to copy the files. %2 is the second positional argument = the destination directory.)

In production, the batch file would probably check that the directories %1 and %2 exist and are really directories; and it should probably accept an optional third argument giving the pattern of the files to be copied.

Enter for /? to read more about how for /r works.