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

后端 未结 3 1705
迷失自我
迷失自我 2021-01-01 06:55

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 fi

相关标签:
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);
      });
    };
    
    0 讨论(0)
  • 2021-01-01 07:08

    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 review what the code returns if you want. The following Logger.log() statement:

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

    will print the dates of the files that were retrieved.

    The above 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.

    It's a good idea to test the code without deleting any files first to make sure that the code is getting the correct files before running a version that deletes anything.

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

    The example below uses the Advanced Google Drive Service. Refer to the documentation for the current way to enable the Advanced Drive Service.

    //To delete a file without first sending it to the trash requires the Advanced Drive API to be enabled
    
    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]);
      }
    };
    
    0 讨论(0)
  • 2021-01-01 07:17

    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.

    0 讨论(0)
提交回复
热议问题