Windows batch file to delete old files and remove empty directories recursively

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:

8 responses to “Windows batch file to delete old files and remove empty directories recursively”

  1. Would you mind updating the article or posting in the comments what all the switches do, would help us all understand it a bit more. Amazing how two little lines can be so powerful!

  2. Hi Trav,
    thanks for your comment. The first line deletes all old files using the forfiles command to find them. The second line removes all empty directories using the rd command. You can read more about how and why the second works here or here.

  3. this script does not works from server, I have to delete files located in another server.

  4. Thank you Jan

    MJ, try:
    forfiles /p “path” /s /m “xxx*xxx.log” /c “cmd /c IF @isdir == FALSE del /S /Q @path”
    You can remove the (*xxx.log)

Leave a Reply

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