Monday, November 07, 2011

Windows Batch Script to Delete Old Files

Few of us know that Windows has some not-so-known tools which mimick Unix's powerful commands. Often we require to delete old files on a Windows machine to provide a means of backup retention policy. You don't need to install Perl or other text manipulation languages - Windows got tools of its own!

You can use a tool called FORFILES (download from Microsoft FTP server if you don't have it!) to select a file or set of files and execute a command on each of them. This allows us to filter files by name, timestamp, size and other attributes, and then perform a command based on their result.

The following are some common examples to use FORFILES to delete or display files older than N days:

Print a warning if the testfile is 3 days old or older:
C:\> forfiles /m testfile.txt /c "cmd /c echo file is too old" /d -3
Delete the testfile if it is is 3 days old or older:
C:\> forfiles /m testfile.txt /c "cmd /c Del testfile.txt " /d -3
Find .xls file that were last modified 60 days ago or older
C:\> FORFILES /M *.xls /C "cmd /c echo @path was changed 60 days ago" /D -60
List the size of all .doc files:
C:\> FORFILES /S /M *.doc /C "cmd /c echo @fsize"
Post a Comment