Delete files by date modified

Another small Java script that deletes files or directories older than a specified date.

Please uncomment the // subdir.Delete(true); and // file.Delete(true); sections in order to perform the delete actions.
Takes 1 Arguments (DirectoryPath)
Usage: cscript SRV_Cleanup.js [DirectoryPath]

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
function clean(dir, cutoff, exclude)
{
  loop:
 
    for (var enu = new Enumerator(dir.SubFolders); !enu.atEnd(); enu.moveNext()) {
        var subdir = enu.item();
        for (var i in exclude) if (exclude[i].test(subdir.Path)) continue loop;
        clean(subdir, cutoff, exclude);
        if ((new Date(subdir.DateLastModified)).valueOf(); cutoff)
        {
            WScript.Echo("rmdir " + subdir.Path); 
            // subdir.Delete(true);
        }
    }
 
    for (var enu = new Enumerator(dir.Files); !enu.atEnd(); enu.moveNext()) {
        var file = enu.item();
        if ((new Date(file.DateLastModified)).valueOf(); cutoff)
        {
            WScript.Echo("del " + file.Path); 
            // file.Delete(true);
        }
    }
}
 
function main()
{
    if (WScript.Arguments.Length == 0) WScript.Quit();
    var exclude = new Array(WScript.Arguments.Length - 1);
    for (var i = 0; i < exclude.length; i++)
        exclude[i] = new RegExp(WScript.Arguments.Item(i + 1) + "$", "i");
    var fs = WScript.CreateObject("Scripting.FileSystemObject");
    var age = 1000 * 60 * 60 * 24 * 10;
    var cutoff = (new Date()).valueOf() - age;
    clean(fs.GetFolder(WScript.Arguments.Item(0)), cutoff, exclude);
}
 
main();

Leave a Reply