Here is a Windows batch file that finds and deletes old files under a specific directory. In a second step the script removes folders that became empty after deleting the (old) files. Note that the scripts works recursively, i.e. it searches for old files and empty folders in any subdirectory under the specified path. One purpose of the script could be the clean up of a backup folder.
forfiles /p [PATH] /s /m [FILE-PATTERN] /d -[DAYS] /c "cmd /c del @path" for /f "delims=" %%d in ('dir [PATH] /s /b /ad ^| sort /r') do rd "%%d"
The placeholders needs to be replaced as follows (without the quotation marks):
- [DAYS] = Max. age of the files in days, e.g. “10”
- [PATH] = Path to search for old files and empty folders, e.g. “C:\Backup\”
- [FILE-PATTERN] = Pattern that matches files to delete, e.g. “*.bkp”
The script has been successfully tested under Windows 7 and Windows Server 2003.
Creating the script was inspired by: