A Small Utility to Delete Files recursively by Date

Posted by Rick Strahl on West-Wind See other posts from West-Wind or by Rick Strahl
Published on Sat, 01 Dec 2012 05:13:05 GMT Indexed on 2012/12/01 11:05 UTC
Read the original article Hit count: 580

Filed under:
|

It's funny, but for me the following seems to be a recurring theme: Every few months or years I end up with a host of files on my server that need pruning selectively and often under program control. Today I realized that my SQL Server logs on my server were really piling up and nearly ran my backup drive out of drive space. So occasionally I need to check on that server drive and clean out files.

Now with a bit of work this can be done with PowerShell or even a complicated DOS batch file, but heck, to me it's always easier to just create a small Console application that handles this sort of thing with a full command line parser and a few extra options, plus in the end I end up with code that I can actually modify and add features to as is invariably the case. No more searching for a script each time :-)

So for my typical copy needs the requirements are:

  • Need to recursively delete files
  • Need to be able to specify a filespec (ie. *.bak)
  • Be able to specify a cut off date before which to delete files
  • And it'd be nice to have an option to send files to the Recycle bin just in case for operator error :-)
    (and yes that came in handy as I blew away my entire database backup folder by accident - oops!)

The end result is a small Console file copy utility that I popped up on Github:

https://github.com/RickStrahl/DeleteFiles

The source code is up there along with the binary file you can just run.

Creating DeleteFiles

It's pretty easy to create a simple utility like DeleteFiles of course, so I'm not going to spend any talking about how it works. You can check it out in the repository or download and compile it. The nice thing about using a full programming language like C over something like PowerShell or batch file is that you can make short work of the recursive tree walking that's required to make this work.

There's very little code, but there's also a very small, self-contained command line parser in there that might be useful that can be plugged into any project - I've been using it quite a bit for just about any Console application I've been building.

If you're like me and don't have the patience or the persistence (that funky syntax requires some 'sticking with it' that I simply can't get over) to get into Powershell coding, having an executable file that I can just copy around or keep in my Utility directory is the only way I'll ever get to reuse this functionality without going on a wild search each time :-)

Anyway, hope some of you might find this useful.

© Rick Strahl, West Wind Technologies, 2005-2012
Posted in Windows  CSharp  

© West-Wind or respective owner

Related posts about Windows

Related posts about CSharp