Delete Dated Subfolders

6:58 am Windows

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

Leave a Comment

Your comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.