Deleting files older than n days using command FORFILES

Posted: October 29, 2012 by Virendra Yaduvanshi in Database Administrator
Tags: , , , , ,

It is always very challenging and energetic know some command line fun magically, as it is sometimes very easier and powerful tips to process commands that way. Here, I would like to say something this type of funny operations with Forfiles command in Windows Server 2003/ Windows Vista /Windows 7/ Windows 8 or higher. Forfiles can process files based on names, file extensions and file life cycle. It’s very easy to find files depending on our search criteria or all files in a directory/or including sub directories that are older than Nth days, or all documents in specific folder that have been changed since a specific date.

The forfiles command can be used with processing options to delete those files, or create a list of all files that match the search criteria.

Forfiles, Selects and executes a command on a file or set of files. This command enables batch processing of files. In conjunction with a SQL Server Agent job, we can easily use this command to delete old database backup files to remove dependencies on items such as SQL Server maintenance plans, the xp_cmdshell extended stored procedure, or VBScript objects. For example, the following command searches the directory c:\test and all its subdirectories for files with the .BAK extension that are older than 10 days

FORFILES /P C:\TEST\ /M .BAK /S /D -10

The parameter /p followed by a directory defines the starting directory, /s includes subdirectories in the search, /m filters the files and folders based on the search criteria, and /D defines the date or a time span.

For more details visit http://technet.microsoft.com/en-us/library/cc753551(v=ws.10).aspx#BKMK_examples

Advertisements
Comments
  1. Andy Hayes says:

    Very useful post Virendra. Thanks for sharing.

    Like

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