July 16, 2012

Deleting old files on Windows

I ran into a situation today where I wanted to script deletion of folders older than a set number days on an old Windows 2000 machine. (The culprit is a commercial SMTP spam and virus filter that does not clean up after itself when it updates. Eventually the drive gets full and no mail comes through.) I found a solution using forfiles but this version of Windows does not have it. I found myself searching the web and gnashing my teeth over the limitations of Windows batch scripting.

That is when I remembered that Windows batch processing can be quite robust if you use the right tools. Namely, you can write JScript (i.e. JavaScript) and Visual Basic scripts for Windows that utilize ActiveX to make use the of whole Windows API. A little googling later and I had the following script:

if (WScript.arguments.length != 2)
    WScript.StdErr.write("Invalid arguments\n");
    WScript.StdErr.write(WScript.ScriptName + " <dir> <no. of days>\n");
var dirname = WScript.arguments.item(0);
var days = parseInt(WScript.arguments.item(1));
var cutoff = new Date();
cutoff.setDate(cutoff.getDate() - days);
WScript.StdOut.write("Deleting files older than: " + cutoff + "\n");

var fso = new ActiveXObject("Scripting.FileSystemObject");
var root = fso.getFolder(dirname);
var subdirs = new Enumerator(root.SubFolders);
for (; !subdirs.atEnd(); subdirs.moveNext())
    var candidate = subdirs.item();
    var lastMod = candidate.DateLastModified;
    if (lastMod < cutoff)
        WScript.StdOut.write("Deleting " + candidate + "\n");

As a nice bonus, the Folder.Delete method works recursively, even on non-empty directories. You invoke the script using the Windows Script Host, cscript.exe:

C:\>cscript //Nologo delete-folders.js C:\dir\to\clean\up 2
Deleting files older than: Sat Jul 14 14:36:56 EDT 2012
Deleting C:\dir\to\clean\up\1342451674
Deleting C:\dir\to\clean\up\1342458973
Deleting C:\dir\to\clean\up\1342463875

Some breadcrumbs if you are looking for the documentation: