Portfolio
My Blog
Scroll down to discover
Search
Categories

Automatically delete old files in Google Drive

November 16, 2021Category : IT & Network

Google Apps Script

First, go to the Google Apps Script homepage and click on Start Scripting.

Script Home

When prompted, sign in with the username and password of the account for the google drive you want to work with.

Login prompt

You should now see the G Suite Developer Hub:

Hub Home

From here, you want to click on New Script up the top left corner.

It will now launch an editor with a skeleton function called myFunction..

In this editor, you can place the code you want to run.

In this case, I’m going to be using the searchFiles method of the DriveApp class and also the Files: delete method of the Advanced Drive Service REST API

The full script is available on my BitBucket repo – direct link here.

Let’s start off with some basic prep before we go searching for files – we only want files older than a given time period – in this case older than 7 days ago:

So, we’ll do the following:

  1. Define a function called GetFilesByDate
  2. Calculate the date in yyyy-MM-dd format that is the cutoff – only give us files older than that
  3. Call DriveApp.searchfiles to return an array of file IDs for files older than that date
  4. Interate through and ignore files that don’t have the .mp4 file extension (use Javascript’s indexOf method for that)
  5. For each file, log some info (for debugging)
  6. Return the filtered array as the result of the function
function GetFilesByDate() {
  var arrFileIDs = [];

  var Threshold = new Date().getTime()-3600*1000*24*7;
    // 30 is the number of days 
    //(3600 seconds = 1 hour, 1000 milliseconds = 1 second, 24 hours = 1 day and 30 days is the duration you wanted
    //needed in yr-month-day format

  var CullDate = new Date(Threshold);
  var strCullDate = Utilities.formatDate(CullDate, "GMT", "yyyy-MM-dd");
  console.info(strCullDate);

  var FileID = "";
  var FileName = "";

  //Create an array of file ID's by date criteria
  var files = DriveApp.searchFiles(
     'modifiedDate < "' + strCullDate + '"');

  while (files.hasNext()) {
    var file = files.next();
    var FileID = file.getId();
    var FileName = file.getName();

    if (FileName.indexOf('.mp4') > -1 ) {
    arrFileIDs.push(FileID);
    console.info('FileID: ' + FileID);
    console.info('Last Updated: ' + file.getLastUpdated());
    console.info('Filename: ' + FileName);
    }
  }

  return arrFileIDs;
  console.info('FileIDs Array: ' + arrFileIDs);
};

Should now look something like this:Script Editor 1

Now, we also need to do something with the array of files returned by that function (and we also need to call it!). So, add the following code, which does the following:

  1. Define a function called DeleteFilesByDate
  2. Call GetFilesByDate
  3. Iterate through each file ID returned and delete it using the Drive.Files.remove method
function DeleteFilesByDate() {
  var arrayIDs = GetFilesByDate();

  for (var i=0; i < arrayIDs.length; i++) {
    console.info('arrayIDs[i]: ' + arrayIDs[i]);
    //This deletes a file without needing to move it to the trash
    var DelResponse = Drive.Files.remove(arrayIDs[i]);
  }
};

Should look like this now:Script Editor 2

Now we want to save the script – either press Ctrl + s or click on the Save icon (the floppy disk icon for those that remember!)Save Icon

Give the project a name and click on OK:

Project Name dialog

Now, you can click on Select Function and choose one to run to test it:

Run Function dialog

Start off with the GetFilesByType function until you are comfortable that it is returning files you would be happy to be deleted!

First things first – you need to authorise the app, so click on Review Permissions when prompted:

Permissions 1

Select the account you logged in with:

Permissions 2

Click on Advanced:

Permissions 3

Click on Go to <Project Name> (unsafe) (it’s OK – we’re authorising to allow this to run because we trust the code otherwise we wouldn’t be doing this!):

Permissions 4

Click on Allow (You’ll see your project name wherever you see Drive Housekeeping on my screenshot):

Permissions Allow

You will see a popup message at the top of the window as shown below while the function is running – it may disappear quickly depending how many files are on your drive:

Running dialog

To check the logs, click on View > Logs or you can press Ctrl + Enter together:

Logs

To test the full function, run the DeleteFilesByDate function in the same way as we did above.

Now, enable the Advanced Drive Service API so we can use it – disabled by default.

Click on Resources > Advanced Google Services

Advanced Google Services

Toggle the Drive API to On:

Toggle (off) default

Toggle on

Click on OK

Save the project again.

Run it again and you’ll be prompted for authorisation again as above – follow the same steps again.

From here, there is one more thing to do – setup a trigger to run this on a frequency of our choosing.

Click on the white arrow top-left to return to the dashboard:Return to dashboard icon

Click on the 3 vertical dots to the right of your project name and click on Triggers:

Triggers

Click on Add Trigger:Triggers 2

Set it up as follows (to run daily between midnight and 1am) and then scroll down and click on Save:

Triggers 3

Now, it will run nightly sometime between midnight and 1am (it may vary in that window every night based on available resource in Google Cloud) and any failures will result in an email to the gmail account associated with the drive.

01.
© Oliver / All rights reserved.
To top