Steven SullivanSteven Sullivan - 16th April 2018

Delete files from Google DriveI 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. It works quite well to delete files from Google Drive.

Note: If you’re looking for a backup script that works well with Google Drive, then look no further. I created a backup script that uses Google Drive as the storage solution. Here’s a backup script. It’s only made to work with RunCloud, but can be very easily modified to work on any Linux server.

I currently 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

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); // Places the file int the Trash folder
        //Drive.Files.remove(File.getId()); // Permanently deletes the file
        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, and delete files from Google Drive:

  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.
  4. If you want to permanently delete the files instead of placing them in the Trash folder then un-comment Drive.Files.remove(File.getId());
  5. The last part is quite easy and it requires you to make the script run once a day. While the Apps Script editor is open, in the menu click Edit -> All your triggers and then set a specific time.

13 thoughts...

  1. Zach says:

    Thanks so much for putting this together — it’s exactly what I’ve been looking for. Hopefully you don’t mind a quick Q from a noob, because I’ve done a bit of searching but I’m not finding any answers unfortunately.

    When I run the script I get this error:

    No item with the given ID could be found, or you do not have permission to access it. (line 12, file “Code”)

    I’ve double-checked my folder IDs and I enabled the Drive API under advanced google services as well as in the cloud platform API dashboard, but the error persists. I’ve also given the script the permissions it needs (See, edit, create, and delete all of your Google Drive files).

    Any idea what might be causing the error?

    1. Hi Zach,

      What’s your code look like? If it’s line 12, I think one of the Folder ID’s is wrong.

  2. Zach says:

    Thanks so much for putting this together — it’s exactly what I’ve been looking for. Hopefully you don’t mind a quick Q from a noob, because I’ve done a bit of searching but I’m not finding any answers unfortunately.

    When I run the script I get this error:

    No item with the given ID could be found, or you do not have permission to access it. (line 12, file “Code”)

    I’ve double-checked my folder IDs and I enabled the Drive API under advanced google services as well as in the cloud platform API dashboard, but the error persists. I’ve also given the script the permissions it needs (See, edit, create, and delete all of your Google Drive files).

    Any idea what might be causing the error?

  3. What Advanced Google Services do you specifically have to enable for files to be permanently trashed?

  4. what if we wanted to delete files that were older than 1 day (for daily backups)? what would need to be changed

    1. Change this line:

      if (new Date() - File.getLastUpdated() > 7 * 24 * 60 * 60 * 1000) {

      To this:

      if (new Date() - File.getLastUpdated() > 1 * 24 * 60 * 60 * 1000) {

  5. cy80rg says:

    Hi Steve, great script! 🙂

    I’m trying to use this – however, I get an error trying to run this…


    Missing ) after argument list. (line 3, file “Code”)

    Infuriating – this looks to do exactly what I need!

    Here’s the code I have…

    function DeleteOldFiles() {
    var Folders = new Array(
    1zKJXKMgY6-ab8wrBoiqDbMSH2xS-veNT ,
    15rQGML-BGzi4-mKngnFnXSuq6Dr9xikS
    );

    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); // Places the file int the Trash folder
    //Drive.Files.remove(File.getId()); // Permanently deletes the file
    Logger.log(‘File ‘ + File.getName() + ‘ was deleted.’);
    }
    }
    }

    if(Logger.getLog() != ”)
    MailApp.sendEmail(‘[email protected]’, ‘Backups have been removed from Google Drive’, Logger.getLog());
    }

    Any thoughts?

    1. cy80rg says:

      Well – sorted that, seems the apostrophes around the folder id are actually needed… doh! 😉

      1. cy80rg says:

        Got that sorted, listing all target directories individually (rather than reliying on sub-folder hierarchy etc) – runs (no errors), but not actually deleting / bin anything yet.
        Have check valid files for binning (changed to last 7 days), but nothing binned yet.

        Will schedule anyway, maybe it takes Drive some time to actually update from this…

        1. cy80rg says:

          Found this on a simmilar thread – which looks like it might be the issue…

          “You need to explicitly enable the Advanced Google Services in your Apps Script project AND in the developers console. If you don’t do both, it won’t work.”

          Problem is, “Advanced Google Services” is a long list of EVERY API. So far, have enabled Google Drive API (for the file functionality) and GMAIL API (for the notification email).

          Still not doing anything, but equally not reporting any errors – Execution Transcript looks to show the script executed successfully…

          1. Sorry about the delay – I accidentally disabled emails from Disqus!

            You are right, the Advanced Google Services needs to be enabled in order to Permanently delete a file. That’s the Drive API. These services must also be enabled in the Google API Console.

            Which piece of code are you using? Are you trying to Trash the file (goes to Trash) or are you trying to permanently delete the file?

      2. cy80rg says:

        Got that sorted, listing all target directories individually (rather than reliying on sub-folder hierarchy etc) – runs (no errors), but not actually deleting / bin anything yet.
        Have check valid files for binning (changed to last 7 days), but nothing binned yet.

        Will schedule anyway, maybe it takes Drive some time to actually update from this…

Leave a Reply

Your email address will not be published. Required fields are marked *