Apps Script - Automatically Delete Files from Google Drive Older than 3 Days - Get List of Files

允我心安 提交于 2019-12-18 13:37:56

问题


I'm using my Google Drive to store motion detection recordings from my IP cameras at home. I'm running the following script (slightly modified) to automatically delete files older than 3 days from my Google Drive:

Automatically delete files in google drive

The script is set to run every morning at around 5am. The problem I'm running into is, when there are too many files to delete, I get an error saying I've exceeded the max write rate. This is because the set trashed command is contained within a for-loop. If I add a sleep to slow down the loop, then I get another error saying the script didn't finish in the allowed time.

I could maybe just run it 2 or 3 times, but that's clunky.

How can I modify this script to have it create a temporary list of the files to be deleted, and when it finally steps out of the loop, execute the delete? I don't have much experience with GAS language and syntax, so specifics would be really awesome.


回答1:


This code will return all the file ID's of files that are older than 30 days old. It is very different than the code referenced in the other post. The code that you are using has a deprecated class in it. DocsList is now deprecated. The code I'm giving you uses DriveApp, and makes use of the searchFiles() method.

Google Documentation - Search Files

gs Script

function getFilesByDate() {
  var arrayOfFileIDs = [];

  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
    //needed in yr-month-day format

  var cutOffDate = new Date(ThirtyDaysBeforeNow);
  var cutOffDateAsString = Utilities.formatDate(cutOffDate, "GMT", "yyyy-MM-dd");
  //Logger.log(cutOffDateAsString);

  var theFileID = "";

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

  while (files.hasNext()) {
    var file = files.next();
    theFileID = file.getId();

    arrayOfFileIDs.push(theFileID);
    //Logger.log('theFileID: ' + theFileID);
    //Logger.log('date last updated: ' + file.getLastUpdated());
  }

  return arrayOfFileIDs;
  //Logger.log('arrayOfFileIDs: ' + arrayOfFileIDs);
};

You can un-comment the Logger.log() statements, run the code, and see what the code returns if you want. There is one Logger.log() statement:

//Logger.log('date last updated: ' + file.getLastUpdated());

That will print the dates of the files that were retrieved. So you can look at that before you delete any files.

That code doesn't delete any files, or set anything to trashed. It just searches files by date, and creates an array of all the file IDs.

So the function to delete or trash the files could first call that function and get a list of all the file ID's to work on.

If you want to delete your files without first setting them to trashed, that can be done.

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.

//This requires the Drive API To be turned on in the Advanced Google Services
//Under the RESOURCES menu, choose ADVANCED GOOGLE SERVICES
function deleteFile(idToDLET) {
  idToDLET = 'the File ID';

  //This deletes a file without needing to move it to the trash
  var rtrnFromDLET = Drive.Files.remove(idToDLET);
}

To call the function that gets the file ID's to delete, it would look like this:

WARNING! THIS DELETES FILES WITHOUT SENDING THEM TO THE TRASH! **** MAKE SURE YOU KNOW WHAT IS BEING DELETED!

function deleteFiles() {
  var arrayIDs = getFilesByDate();

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



回答2:


I came up with another solution. This only works if your Google Drive files are synced to your hard drive.

If your Google Drive files are synced to your hard drive, then if you delete them in the local hard drive folder, they also will be deleted from Google Drive as well. So, the mission then becomes how to automatically delete files that are greater than X days old from your Google folder(s).

This is a Windows Powershell script which will allow you to do just that: https://gallery.technet.microsoft.com/scriptcenter/Delete-files-older-than-x-13b29c09

Running the script with this configuration:

powershell -file c:\users\owner\documents\windows\deleteold\deleteold.ps1 -FolderPath "C:\Users\owner\Google Drive\iSpy\video\Bedroom" -FileAge 30 -logfile c:\users\owner\documents\windows\deleteold\logs\Bedroom.log -CreateTime -NoFolder

I am able to delete all iSpy files older than 30 days from my synced Google Drive "Bedroom" folder.

Following these instructions:

http://blogs.technet.com/b/heyscriptingguy/archive/2012/08/11/weekend-scripter-use-the-windows-task-scheduler-to-run-a-windows-powershell-script.aspx

I am able to run the script automatically using Windows Task Scheduler.

Problem solved.




回答3:


Using the solution that Sandy posted above, I modified it to be folder specific.

function getOldFileIDs() {
  var fileIDs = [];
  // Old date is 30 days
  var oldDate = new Date().getTime() - 3600*1000*24*30;
  var cutOffDate = Utilities.formatDate(new Date(oldDate), "GMT", "yyyy-MM-dd");

  // Get folderID using the URL on google drive
  var folder = DriveApp.getFolderById('XXXXXXX');
  var files = folder.searchFiles('modifiedDate < "' + cutOffDate + '"');

  while (files.hasNext()) {
    var file = files.next();
    fileIDs.push(file.getId());
    Logger.log('ID: ' + file.getId() + ', Name: ' + file.getName());
  }
  return fileIDs;
};

function deleteFiles() {
  var fileIDs = getOldFileIDs();
  fileIDs.forEach(function(fileID) {
    DriveApp.getFileById(fileID).setTrashed(true);
  });
};


来源:https://stackoverflow.com/questions/28618964/apps-script-automatically-delete-files-from-google-drive-older-than-3-days-g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!