Search

Monday, 07 December 2009

Finding old files

I haven't written anything about Powershell for quite a long time, there is a reason for that - I haven't been using it much. However, that situation changed a week or so ago.

At Convallis we perform a daily backup of all our working databases and files. This backup is done using PerfectBackup which we find to be a very useful service, which allows us to 'set it and forget it' when it comes to backing up our data. But it does come with one small drawback, if databases are backed up every day with a unique name each time over the course of a few weeks the quantity of files created can become quite significant and with each being several megabytes in size it's not a small amount of space required to store them. So over time these backups start filling up the online backup quota.

I normally alleviate that problem every once in a while by deleting the older files, but I thought it was about time that that process was automated. In theory it should be a relatively simple thing to do, just a case of filtering the files to find those created before a certain date. I didn't see the point in writing a program to do this when I knew that an appropriate command in Powershell could do it for me.

Thus I created the following command:
get-childitem c:\backup -filter *.bak | where-object { $_.LastWriteTime -lt (get-date).AddDays(-42)} | remove-item

What this command does is to list all the files in the c:\backup folder with a file extension 'bak'. That list is then piped into a command which performs an enquiry on the data piped into it (a list of objects describing the files is what is returned from get-childitem). The enquiry says that only files with a last write time (last time modified) less than the current date less 42 days should be returned, i.e. I want to retain files younger than 6 weeks old. Finally that list of files is piped into a command which deletes each one from the hard disk.

Having figured the command out I wanted to schedule it to run once an month, so to do this I created a scheduled task which invokes Powershell. I then altered the command line, adding a -command item followed by the above command encased in double quotes. So that's it, I now have a task that runs once a month deleting all backup files that are more than 6 weeks old.

Comments
To leave a comment please login
Register