Tuesday, 23 August 2011

Script to delete files of n days old.... Windows server


In one of the windows servers, I am storing backup files of a database server. As per our policy we have to keep backup files for 30 days. As in the partition size where I am storing backup files is small, so I have to regularly delete backup files to manage free space in that partition. I could easily write a shell script in Linux to delete 30 days old file, but I was not sure how to do it in the Windows 2003 server. Then I came to know about Forfiles ( ) , I used it and wrote a batch script which will delete 30 days old file everyday.

The script is as follows:

@echo off & setlocal

Create a variable to store the name of the temporary file to capture the output. If you do not want to capture the file names that are deleted, you can skip the temporary file part.

set tempmail=%temp%\solardb_delete.txt

Just writing a blank line to the temporary file

-p option of forfile specifies the path where it will look for files, -d -30 specifies to select files last modified 30 days before current date (its minus 30). –c specifies the command to execute. The command first appends the filename to be deleted into the temporary file and then deletes the file.

forfiles -p F:\MySQLBackup\Today -d -30 -c “cmd /c echo deleting @FILE .>>%tempmail% & del @FILE”

Next part of this script is to send the mail alert, also sending the temporary file containing the deleted file names as an attachment in the mail. For this I used a php script (the reason of using php script is that, I can use external SMTP server of rediff to send the mail and do not have dependency on local SMTP sever. Otherwise this can also be done through a batch script), you can use any script/program as you like to the send mail alert. Otherwise you can skip the following part.

move %tempmail% F:\php_script\output

set tempmail=


php F:\php_script\mysql_backup_delete.php

del /Q F:\php_script\output\solardb_delete.txt

জয় আই অসম,
প্রণব শর্মা