Steven SullivanSteven Sullivan - 16th April 2018

I created a little script to delete files in specific folders older than 7 days on Google Drive, and if something is deleted it sends you an email! It doesn’t permanently delete them, it just puts them in the Trashed folder. Works quite well to delete files from Google Drive.

I have a backup solution for my servers whereby my Google Drive structure looks like this:

  • Server Backups
    • Server 1
      • File 1
      • File 2
      • File 3
    • Server 35
      • File 1
      • File 2
      • File 3

Note: I’ll be adding a very simplistic backup script soon.

The File 1, 2, or 3 can be MySQL backups, application data backups, etc.

Google Apps Script to delete files older than 7 Days in Google Drive

 

function DeleteOldFiles() {
  var Folders = new Array(
    'FOLDER_ID_HERE',
    'FOLDER_ID_HERE'
  );
  var Files;
  
  Logger.clear();
  
  for each (var FolderID in Folders) {
    Folder = DriveApp.getFolderById(FolderID)
    Files = Folder.getFiles();
    
    while (Files.hasNext()) {
      var File = Files.next();
      
      if (new Date() - File.getLastUpdated() > 7 * 24 * 60 * 60 * 1000) {
        File.setTrashed(true);
        Logger.log('File ' + File.getName() + ' was deleted.');
      }
    }
  }
  
  if(Logger.getLog() != '')
    MailApp.sendEmail('YOUR_EMAIL_ADDRESS', 'Backups have been removed from Google Drive', Logger.getLog());
}

 

To complete the script:

  1. Change FOLDER_ID_HERE with the folder ID’s you see in Google Drive. You can get them by double-clicking the folder and the URL structure will be something like this: https://drive.google.com/drive/folders/1Wx81C1hjghjBfgddfgfgmFeMfzdfgHyTdfgkLgdfg3yz
  2. If you have more folders, just keep adding the ID’s to the Array.
  3. Change YOUR_EMAIL_ADDRESS to your own email address to get notifications.