0

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.

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120

2 Answers2

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
  • 34,892
  • 8
  • 45
  • 61
  • 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,585
  • 1
  • 20
  • 38