3

I want to delete all the folders from a directory except the 2 most recently updated folders (Last modified date).

I want to do this using the command line. How do I do it?

Below is the code to display folders sorted by last modified time:

dir /ad-h /od

I tried using FOR /D command:

for /d "skip=2 tokens=*" %G in ("dir /ad-h /od") DO echo going to delete %G

But I get the below error message:

"skip=2 tokens=*" was unexpected at this time.

How do I do it?

Darren Shewry
  • 10,179
  • 4
  • 50
  • 46
DDK
  • 1,032
  • 18
  • 39

1 Answers1

3
for /f "skip=2 delims=" %G in ('dir /B /ad-h /o-d "d:\your path" ') DO echo going to delete "%G"

For /f to process lines of "output" from single-quoted DIR...

Delims= is better. tokens=* will work here, but suppresses leading spaces.

/b to suppress header output from dir

/o-d for REVERSE-date order. You want to KEEP the two skipped dirs, which occur FIRS in a reverse-date sort.

...good echo safety measure.

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • in `/ad-h` /ad selects only directories and the -h removes hidden folders from the list. – foxidrive Jul 08 '13 at 11:30
  • @Magoo You might just have saved me from more headaches. See here https://stackoverflow.com/questions/31796149/windows-batch-script-to-only-keep-the-n-latest-folders-in-a-directory and here https://stackoverflow.com/questions/31787056/windows-batch-script-to-backup-local-mysql-databases-only-keep-n-latest-folder . Besides this I read your profile and like to reach out to you personally NOT related to IT but to what you write in your profile. Bottom line: So true it hurts and makes me angry. It's not even IT, it is the incompetent HR puppets that ruin everything. Any ways. How can I talk 2 you? – lowtechsun Aug 04 '15 at 10:38
  • @Magoo and yes indeed it works, see linked questions with my answers now, though I am changing `del` to `rd` to also delete the folders **with** they contents. – lowtechsun Aug 04 '15 at 11:52
  • Where to specify path ? – Paul Jul 03 '20 at 10:06
  • @Paul: Fixed. Note use of rabbit's ears to allow spaces in pathname to be correctly processed – Magoo Jul 03 '20 at 21:11