Wednesday, February 17, 2010

Deletes files older than a number of days in a specified directory

It's not quite easy to achieve that functionality with Windows batch file. However with built-in command wscript.exe or cscript.exe, we can write some jscript:
/**
* Deletes files older than a number of days in a specified directory
*/

function deleteFilesInFolder(folder) {
  WScript.echo(folder);
  for (var it = new Enumerator(folder.Files); !it.atEnd(); it.moveNext()) {
    var file = it.item();
    if (file.DateLastModified < nDaysAgo) {
      if (testing)
        WScript.echo("  " + file.name);
      else
        file.Delete(true);
    }
  }

  if (recursive)
    for (var it = new Enumerator(folder.SubFolders); !it.atEnd(); it.moveNext()) {
      deleteFilesInFolder(it.item());
    }
}

var usage = "Usage: cscript|wscript delOldFiles.js [-t] [-r] [-h|-?] [dir] [#Days]\n" +
    "-h|-?: This usage message\n" +
    "   -t: Test mode, no real deletion, just show files to be deleted\n" +
    "   -r: Recursive, file in subdirectories will be deleted as well\n" +
    "  dir: The specified directory. Default is current dir\n" +
    "#Days: Delete files older than this # of days. Default is 7";

// arguments handling
var testing = false;
var recursive = false;
var dir;
var nDays;

for (i = 0; i < WScript.arguments.length; i++) {
  arg = WScript.arguments(i);

  if (arg == "-h" || arg == "-?") {
    WScript.echo(usage);
    WScript.quit();
  }
  else if (arg == "-t")
    testing = true;
  else if (arg == "-r")
    recursive = true;
  else if (isNaN(parseInt(arg)))
    dir = arg;
  else 
    nDays = arg;
}
nDays = nDays == null ? 7 : nDays;
dir = dir == null ? "." : dir;
//WScript.echo("-t=" + testing + ", -r=" + recursive + ", dir=" + dir + ", day=" + nDays);

// Compute date
var nDaysAgo = new Date();
nDaysAgo.setDate(nDaysAgo.getDate() - nDays);

// Delete files in the dir
deleteFilesInFolder(WScript.CreateObject("Scripting.FileSystemObject").GetFolder(dir));
Ref: Vincent Robert's example

No comments: