Link to home
Start Free TrialLog in
Avatar of Zherebets
ZherebetsFlag for United States of America

asked on

Batch script to move specific number of files from one folder to another

I couldn't find any answers to this specific question so I am posting in hopes that someone can assist.  I have multiple folders that have several thousand files in each one.  I would like to have a batch file that will allow me to select the first 2000 files from an already existing folder, create a new folder in the same directory and copy them over to the new folder.  I'm sure this require some sort of looping, but I am not too familiar with how that works as I have never written any looping code before.  It would be perfect if someone could write the script for me so all I have to do is fill in the folder location and destination folder creation and file copy location.

If I can provide any more details that will assist someone in providing a solution to my quandary.

Thanks,
Phil
Avatar of t0t0
t0t0
Flag of United Kingdom of Great Britain and Northern Ireland image

Please give this a try....


SETLOCAL ENABLEDELAYEDEXPANSION

SET Source=C:\Temp
SET Destination=%Source%\NewFolder

IF NOT EXIST "%Destination%\" MD "%Destination%"

SET Count=0

FOR /F "TOKENS=*" %%a IN ('DIR /A-D /B "%Source%\*.*') DO (
   SET /A Count+=1
   MOVE "%%a" "%Destination%\"
   IF !Count!==2000 GOTO ExitLoop
)

:ExitLoop
In the above code, you should change 'Source' to the folder containing the files you want to move.

Also, change the name of the destination folder. As you can see, this is created off the 'source' folder.

Strictly speaking, it's considered bad programming practice to prematurely jump out of a loop. The correct method would normally be as follows:


SETLOCAL ENABLEDELAYEDEXPANSION

SET Source=C:\Temp
SET Destination=%Source%\NewFolder

IF NOT EXIST "%Destination%\" MD "%Destination%"

SET Count=0

FOR /F "TOKENS=*" %%a IN ('DIR /A-D /B "%Source%\*.*') DO (
   SET /A Count+=1
   IF !Count! LEQ 2000 (
      MOVE "%%a" "%Destination%\"
   )
)
Oops! There's a typo in the FOR lines above.... They're supposed to include closing brackets as in:

FOR /F "TOKENS=*" %%a IN ('DIR /A-D /B "%Source%\*.*"') DO (



Avatar of Zherebets

ASKER

t0t0,

Thanks for the assistance, but I'm having a problem moving the files into the newly created directory.  I keep getting the following error:

The system cannot find the file 'DIR /A-D /B "MyDestination\*.*'".

MyDestination = the path that I am using

Any ideas?

Thanks,
Phil
ASKER CERTIFIED SOLUTION
Avatar of t0t0
t0t0
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for the help, t0t0.
Wow !! That was quick.... Thank you.