How do you Delete files Older than a given date?

So I got asked if I knew a way of deleting files from a folder that were older than a given date.  I knew this could be done with the Windows OS, bust just how. The Delete command itself is not good enough for the job, so it was time to write a batch file to do the job. I also thought why re-invent the wheel as someone else must have tried this so a quick search on the Internet and I found some information and put it all together. Here is my Batch file, just copy and paste into Notepad.exe and save as DELOLD.bat

   1: @ECHO OFF
   2: SET OLDERTHAN=%1
   3: IF NOT DEFINED OLDERTHAN GOTO SYNTAX
   4:  
   5: echo. >> ~~~FILES_TO_KEEP.TXT~
   6: for /f "tokens=*" %%a IN ('xcopy *.* /d:%1 /L /I null') do if exist %%~nxa echo %%~nxa >> ~~~FILES_TO_KEEP.TXT~
   7: for /f "tokens=*" %%a IN ('xcopy *.* /L /I /EXCLUDE:~~~FILES_TO_KEEP.TXT~ null') do if exist "%%~nxa" del "%%~nxa"
   8: del ~~~FILES_TO_KEEP.TXT~
   9:  
  10: GOTO END
  11:  
  12: :SYNTAX
  13: ECHO.
  14: ECHO USAGE:
  15: ECHO DELOLD mm-dd-yyyy
  16: ECHO   Where mm-dd-yyyy is the date prior to which you want to delete files.
  17: ECHO.
  18: ECHO EX: "DELOLD 10-17-2008" Deletes files older than October, 17 2008.
  19: GOTO END
  20:  
  21: :END

You need to enter the date in the given format of mm-dd-yyyy as the XCOPY command needs it this way. Place the batch file in the folder that you need to delete the files from and execute the batch file.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: