Kevin Baker
Kevin Baker

Reputation: 13

Keeping the last 10 folders, delete the rest

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.

Upvotes: 0

Views: 1402

Answers (2)

Dipto
Dipto

Reputation: 2738

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

Upvotes: 0

Endoro
Endoro

Reputation: 37569

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"

Upvotes: 2

Related Questions