3

Can someone provide a batch script that will delete all but the X most recently modified folders in a directory. I've looked at How do I delete old files from a directory while keeping the most recent ones on Windows, but that was based on an absolute time window rather than a relative ordering of modification dates.

Thanks for any help

Community
  • 1
  • 1
rimsky
  • 1,063
  • 2
  • 15
  • 24

1 Answers1

1

This will keep the 10 latest log files based on modification date:

@echo off
for /f "skip=10 delims=" %%a in (' dir *.log /o-d /a-d /b ') do echo del "%%a"

Remove the echo to make it perform the deletions rather than just display them.

foxidrive
  • 37,659
  • 8
  • 47
  • 67
  • used rd /S /Q to silently remove entire non-empty directories, but this worked. Thanks! – rimsky Sep 01 '13 at 03:40
  • For the latest 5 folders I used: FOR /f "skip=5 delims=" %%a IN (' DIR %DEST% /o-d /b') DO RD /S /Q "%DEST%\%%a", where %DEST% is the path to the folder. – AudioDroid Apr 01 '15 at 11:49