I am very new to writing batch files and I cannot get the two newest files from one folder to copy into another folder. I have new folders automatically created everyday and I want to have them automatically move to the opposite place rather than having to move them manually everyday.
I was able to get the newest folder to move over but whenever I tried anything to get the second I had no luck. Any advice would be appreciated

  • You can create a symbolic link to connect those directories so that they automatically saved in your preferred folder. – Biswapriyo Jul 21 '17 at 20:22
  • Or can you have them automatically created in the correct location using whatever function is creating them? – HackSlash Jul 21 '17 at 21:04
  • Sort files backwards with Dir /B /O-D /A-D
  • Number the files with findstr /n
  • If number less or equal Xnewest - move

@Echo off
Set "Xnewest=2"
For /F "tokens=1* delims=:" %%A in (
  'Dir /B /A-D /O-D ^| Findstr /N "^"'
) Do If %%A Leq %Xnewest% echo Move "%%B" "X:\Path\to\dest\"

If the output looks OK, remove the echo in the last line.

Sample output:

> dir /A-D/O-D
 Directory of A:\
07/21/2017  23:19               315 SU_1232190.cmd
07/21/2017  14:58               778 SO_45225802.cmd
07/19/2017  10:51               158 PassMinMax.cmd
07/19/2017  00:50                37 WhoStartedMe.cmd
07/18/2017  01:32             1.222 SO_45137227.cmd
               5 File(s)          2.510 bytes
               0 Dir(s)   1.049.776.128 bytes free
> SU_1232190.cmd
Move "SU_1232190.cmd" "X:\Past\to\dest\"
Move "SO_45225802.cmd" "X:\Past\to\dest\"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.