How to delete files that are older than 'N' days in specified directories

This JSS script will be for a scheduled process trigger that deletes files that are older than 'N' (Number of) days in specified directories.

Now let us see how to do this. The following steps will configure CompleteFTP to perform this trigger:

  1. Define the folders which you want the script to work on. The folders below include some files, which are older than 'N' days.


  2. Go to the CompleteFTP Manager, open the Folder panel, then create 3 Windows Folders which match the 3 folders in the step 1.

  3. Go to Events panel, select Schedule event and set it up as Every '1' day (although you can set any time/number of days you wish).

  4. Then add the script below in to the JSS type script.

    var MAX_FILE_AGE_DAYS = 30;
    
    var foldersToPurge = [
    	"/Directory1",
    	"/Directory2",
    	"/Directory3"
    ];
    
    // returns the difference between two days in days
    function subtractDates(date1, date2) {
    
    	// Convert both dates to milliseconds
    	var date1ms = date1.getTime();
    	var date2ms = date2.getTime();
    
    	// Calculate the difference in milliseconds
    	var ONE_DAY = 1000*60*60*24;
    	return (date2ms - date1ms)/ONE_DAY; 
    }
    
    for (var i in foldersToPurge) {
        
    	// get listing of folder
    	var folder = system.getFile(foldersToPurge[i]);
    	var files = folder.getFiles();
    
    	for (var j in files) {
    		var file = files[j];
    		if (file.isFolder)
    			continue;
    
    		// Work out the age of the file
    		var now = new Date();
    		var modTime = file.modifiedTime;
    		var age = subtractDates(modTime, now);
    
    		// If it's old then delete it
    		if (age > MAX_FILE_AGE_DAYS) {
    			console.log(file.fullPath + " is " + Math.floor(age) + " old - deleting");
    			file.remove();
    		}
    	}
    }
    
  5. The process triggers will look like this:

  6. Apply the changes.

  7. You should check the relevant folders after the time you set (1 day), the files which are older than 30 days (set in the code) will be deleted as below:

    If the trigger is checked, it will run continuously and will automatically check these folders every day.