I have a backup scheme that creates a folder structure such as this…


X:\BACKUP
X:\BACKUP\SERVER1
X:\BACKUP\SERVER1\BACKUP-10-27-2012
X:\BACKUP\SERVER1\BACKUP-10-28-2012
X:\BACKUP\SERVER1\BACKUP-10-29-2012
X:\BACKUP\SERVER1\BACKUP-10-30-2012
X:\BACKUP\SERVER2
X:\BACKUP\SERVER2\BACKUP-10-27-2012
X:\BACKUP\SERVER2\BACKUP-10-28-2012
X:\BACKUP\SERVER2\BACKUP-10-29-2012
X:\BACKUP\SERVER2\BACKUP-10-30-2012

I only wanted to keep the last 2 backups in each subfolder. Here is a script that will do just that.

Contents of x:\backup\cleanup-backups.bat:


@echo off
x:
cd \backup
for /f "tokens=*" %%i in ('dir /b /a:d') do (
pushd %%i
for /f "skip=2 tokens=*" %%g in ('dir /a:d /b /o:-d') do rmdir "%%g" /s /q
popd
)
exit

Worked like a charm. Afterwards I ended up with:


X:\BACKUP
X:\BACKUP\SERVER1
X:\BACKUP\SERVER1\BACKUP-10-29-2012
X:\BACKUP\SERVER1\BACKUP-10-30-2012
X:\BACKUP\SERVER2
X:\BACKUP\SERVER2\BACKUP-10-29-2012
X:\BACKUP\SERVER2\BACKUP-10-30-2012