Search code examples
google-apps-scriptgoogle-drive-api

Google Script, Delete files within a folder based on the last modified date


I am trying to create a script that will work through a shared drive once a week, and delete anything that has not been modified within the last 90 days.

I have found a few scripts on here that do not seem to work as I intended them to.

The script I currently have is below, but for some reason it does not seem to work, yet it seems as though it should.

It seems to identify the files, but does not seem to move them to the trash.

Any tips would be welcome thank you.

function getOldFileIDs() {
  var fileIDs = [];
  // Old date is 90 days
  var oldDate = new Date().getTime() - 3600*1000*24*90;
  var cutOffDate = Utilities.formatDate(new Date(oldDate), "GMT", "yyyy-MM-dd");

  // Get folderID using the URL on google drive
  var folder = DriveApp.getFolderById('1ClpJ8uwlVRc9zT4q2AsatEQBvPFTH5Eu');
  var files = folder.searchFiles('modifiedDate < "' + cutOffDate + '"');

  while (files.hasNext()) {
    var file = files.next();
    fileIDs.push(file.getId());
    Logger.log('ID: ' + file.getId() + ', Name: ' + file.getName());
  }
  return fileIDs;
};

function deleteFiles() {
  var fileIDs = getOldFileIDs();
  fileIDs.forEach(function(fileID) {
    DriveApp.getFileById(fileID).setTrashed(true);
  });
};

Solution

  • Unfortunately I was having a bad day, what I forgot to do is change the folder id from the test ID to the working ID