Windows Server – File Cleanup Script for Task Scheduler – Delete Files Older Than X Days

Every time I’ve written this script I never save it and have to end up googling it again to tweak behavior to the way I want.

So today I’m writing it down permanently!

Side Note – It’s funny how it always ends up being on some piece of legacy infrastructure I’ve inherited running Windows Server 2012 or 2008 no matter what job position I’ve been in.

This recurses into the subdirectories and deletes files older than 60 days.

It also outputs what was deleted to the specified log file.

What I did was create this as “cleanup.bat” and then created a Task Scheduler entry to call the batch file.

ForFiles /p "D:\MyCoolDirectory" /s /d -60 /c "cmd /c echo Deleting @file >> D:\deletion_output.log 2>&1"
ForFiles /p "D:\MyCoolDirectory" /s /d -60 /c "cmd /c del /q @file >> D:\deletion_output.log 2>&1"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s