Tec(h)tonic

Insights into building a solid I.T. foundation in the mid-size business world.

.BAT file to delete files older than x days and empty folders

This is a valuable little piece of code – useful for maintaining otherwise unmonitored file repositories. Set this up to be autorun by the Task Scheduler on a predetermined basis. Note that the forfiles command is included with Windows Vista and later and Windows Server 2003 and later.


@ECHO OFF
REM delete any files older than <x> days
forfiles /p <directory> /s /d -<x> /c "cmd /c del /q @PATH"
REM delete empty folders
REM insert 'echo' between /c del to test command
for /f "delims=" %%d in ('dir <directory> /s /b /ad ^| sort /r') do rd "%%d"


Leave a Reply

Your email address will not be published. Required fields are marked *