I've seen many examples of how to keep the last x files and delete the rest, but having trouble changing the code to work for folders. I'm looking for a batch file to look into a folder (C:\backups) and delete all but the last 10 folders.
Asked
Active
Viewed 1,383 times
0
-
what do you mean by `last folders`? `last modified` or `last created` or alphabetically last? – Dipto Jan 11 '14 at 18:58
-
last created the folder are called 20140101, 20140102.. YYYYMMDD – Kevin Baker Jan 11 '14 at 19:01
-
show your existing code – Dipto Jan 11 '14 at 20:29
2 Answers
2
this works on my shell, you need only minor changes:
for /f "skip=10delims=" %A in ('dir /b /ad /o-n "%UserProfile%\test\*"') do @echo rd /s /q "%UserProfile%\test\%~A"

Endoro
- 37,015
- 8
- 50
- 63
-
Servus nach Österreich :) Trying your answer on this question https://stackoverflow.com/questions/31787056/windows-batch-file-to-backup-local-mysql-databases-only-keep-n-latest-folders wanting to keep only 3 (for testing only) latest folders but it does not work. Tells me File Not Found. Can you please please help perhaps if you have a little moment? I have `for /f "skip=3 delims=" %A in ('dir /b /ad /o-n "%backupDir%\%dirName%\*"') do @echo rd /s /q "%backupDir%\%dirName%\%~A"` but it does not want to delete the folders. I have no clue why. Thank you heaps for any help. – lowtechsun Aug 03 '15 at 16:55
0
The following may work, not tested though.
@echo off
for /d %%k in (*) do set count=%%k
:loop1
dir /ad /b /on > dirlst
set /p TOP=<dirlst
del dirlst
rd %TOP%
set /a count=count-1
if %count% GTR 10 goto loop1

Dipto
- 2,720
- 2
- 22
- 42