Automatically delete files in google drive

16,116

based on another post by Tiziano Solignani and myself, here is a script that does the job... Please uncomment the setTrashed statement when you have it fully tested in the logger. Don't forget to change the email adress as well.

function DeleteMyJpegs() {
    var pageSize = 200;
    var files = null;
    var token = null;
    var i = null;
    var ThirtyDaysBeforeNow = new Date().getTime()-3600*1000*24*30 ;// 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
    Logger.clear()

    do {
    var result = DocsList.getAllFilesForPaging(pageSize, token);
    var files = result.getFiles()
    var token = result.getToken();
        for(n=0;n<files.length;++n){
            if(files[n].getName().toLowerCase().match('.jpg')=='.jpg' && files[n].getDateCreated().getTime()<ThirtyDaysBeforeNow){
    //            files[n].setTrashed(true)
                Logger.log(files[n].getName()+' created on '+Utilities.formatDate(files[n].getDateCreated(), 'GMT','MMM-dd-yyyy'))
            }
          }    
     } while (files.length == pageSize);

      MailApp.sendEmail('[email protected]', 'Script AUTODELETE Jpegs report', Logger.getLog());

} 

EDIT : If you prefer to look at the size of the files in your drive, you could modify this do do some math on the jpg's size and other filetypes that take space) quite easily... and delete some files accordingly. This is a example to show how to handle the situation.

Share:
16,116
Admin
Author by

Admin

Updated on August 02, 2022

Comments

  • Admin
    Admin over 1 year

    Is there an app or script I can use that will automatically delete files (specifically .jpg) in my root google drive directory after 30 days or when my google drive is close to getting full.

    I have .jpg attachments sent over from my email automatically to my google drive.It is just filling up my google drive space and I would like them to be automatically deleted.

    Thanks.

  • Admin
    Admin about 11 years
    Thank you for the response. It seems to be working. How would I modify it if I wanted to change it to 10 days instead of 30. In addition, do you know if it is possible to have them permanently deleted instead of it being sent to the trash? Thank you.
  • Serge insas
    Serge insas about 11 years
    I edited the code (btw there was a typo in the math operation) and added a comment to show you how to modify the number of days. I'm not sure one can empty the trash with gas.
  • Admin
    Admin about 11 years
    Thanks for the fix. Instead of sending the files to the trash, I found this to delete files permanently. Will this information help? developers.google.com/drive/v2/reference/files/delete
  • blindguy
    blindguy about 8 years
    DocsList has been replaced by DriveApps.getFiles()