Delete files from Google Drive folders after X days (Apps Script)

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

Chrome V8 Engine (Now enabled by default)

function DeleteOldFiles() {
  var Folders = new Array(
    'FOLDER_ID_HERE',
    'FOLDER_ID_HERE'
  );
  var Files;

  Logger.clear();

  for (var key in Folders) {
    Folder = DriveApp.getFolderById(Folders[key])
    Files = Folder.getFiles();
	
	Logger.log('Opening Folder: ' + Folder.getName());

    while (Files.hasNext()) {
      var File = Files.next();

      if (new Date() - File.getLastUpdated() > 7 * 24 * 60 * 60 * 1000) {
        File.setTrashed(true); // Places the file in 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());
}

Old Runtime:

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.

26 thoughts...

  1. chuckiefinster says:

    Hello. This script worked for quite some time but now when it runs I get error message, “SyntaxError: Unexpected identifier (line 10, file “Code.gs” and line 10 is “for each (var FolderID in Folders) {”

    How would I fix this?

    1. It sounds like you’ve enabled the new Chrome V8 Runtime.

      To disable this, select Run in the menu, then Disable New Apps Script Runtime Powered By Chrome V8.

      1. chuckiefinster says:

        Thanks for that. I disabled but now receive this “We’re sorry, a server error occurred. Please wait a bit and try again”

        1. Not sure what this could be. It’s certainly not related to the script. It sounds like a Google error.

  2. s. fauzan says:

    Hai, i try to delete file withous going to trash, but have an error on
    Drive.Files.remove(File.getId());
    when it dows not have comment “//”

    how to fix this ?

    here the screenshot http://i.imgur.com/ZuxBPcn.png

  3. Leonard says:

    Very useful, thanks. What about EXCLUDING specific file extension from deleting?

  4. feklaar says:

    Thanks for the nice script. I have one issue, my company would like to utilize this in a shared folder, so anytime a file is placed in the shared folder, it will be deleted after 24hours. My problem is that it appears this script must be run be the individual that created the file. I get a permission error when attempting to delete the file even thought I created the folder.

    Is there a way to modify the permissions of the folder to allow me to delete any files in a given folder?
    Thanks!

    1. It’s not possible. Google states this:

      If you’re the owner of the file, others can view it until you permanently delete the file. If you’re not the owner, others can see the file even if you empty your trash.

  5. Bryan Gossuin says:

    Can you do the same thing but for folders and not files?

    1. Hi Bryan,

      At this time I’m not aware of there being a ‘last modified’ function for folders. Currently, all we can get is the time it was created,

      1. Eric Roberts says:

        Deleting a folder (vs file) 30 days after it was created is exactly what I’m looking to do

        How would this script be changed if I wanted to delete a folder 30 days after it’s created date?

  6. Morris Coyle says:

    Excellent post -thank you, it was just what i was looking for. Is there anyway to modify the script to look for files names starting with a certain string? I’ve been playing around with it for a couple of hours but not getting anywhere

    1. Yeah sure, something like this:

      The ^ in the script means “starts with”.

        for each (var FolderID in Folders) {
          Folder = DriveApp.getFolderById(FolderID)
          Files = Folder.getFiles();
          while (Files.hasNext()) {
            var File = Files.next();
            var FileName = File.getName();
            if (new Date() - File.getLastUpdated() > 7 * 24 * 60 * 60 * 1000 && FileName.match(/^starts_with/) !== null) {
              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.');
            }
          }
        }
      
  7. 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.

  8. 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?

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

  10. 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) {

  11. 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 *

 

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>