Thursday 24 January 2013

Auto delete files older than x number of days

Following script is ideal where you want to clear the space from backup repository and keep files created in last x number of day, I've been utilizing this to delete all SQL backup files *.bak from backup repository D:\foldername where anything older than 6 days should be deleted.

Create a batch file  Script.bat and Add it the Scheduled Tasks to run daily/weekly/monthly


forfiles /p "D:\foldername" /m *.bak /s /d -6 /c "cmd /c del @PATH"


Switches used:

/P    pathname
/M    searchmask
/S   recuse and check all the subdirectories
/D    date
Selects files with a last modified date greater than or equal to (+), or less than or equal to (-), the specified date using the "dd/MM/yyyy" format; or selects files with a last modified date greater than or equal to (+) the current date plus "dd" days, or less than or equal to (-) the current date minus "dd" days. A valid "dd"  number of days can be any number in the range of 0 - 32768. "+" is taken as default sign if not specified.


/C    command       Indicates the command to execute for each file.
                    Command strings should be wrapped in double quotes.

                    The default command is "cmd /c echo @file".

                    The following variables can be used in the command string:


                    @file    - returns the name of the file.
                    @fname   - returns the file name without extension.
                    @ext     - returns only the extension of the file.
                    @path    - returns the full path of the file.
                    @relpath - returns the relative path of the file.
                    @isdir   - returns "TRUE" if a file type is a directory, and "FALSE" for files.
                    @fsize   - returns the size of the file in bytes.
                    @fdate   - returns the last modified date of the file.
                    @ftime   - returns the last modified time of the file.

Internal CMD.exe commands should be preceded with "cmd /c".

No comments:

Post a Comment