且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Google Apps脚本可永久删除旧文件并保留最后100个文件

更新时间:2023-12-04 20:58:10

正如我在评论中说的那样,您所引用的脚本与您想要的不是很遥远...但是我承认您的情况要复杂一些因此,我们可以说这将是政治的另一个例外;-)

As I said in the comments, the script you referred to was not very far from what you want... but I admit your situation is a bit more complex so let's say this will be another exception to sto politics ;-)

也就是说,我没有对代码进行彻底的测试,因此可能需要进行一些调整.我在整个脚本中留下了一些注释日志,以测试中间结果,请毫不犹豫地使用它们.另外,请考虑更新邮件地址,不要忘记setTrashed可以手动反转;-)(在尝试新代码时更好)

That said, I didn't test this code thoroughly so it will probably need some tuning. I left a couple of commented logs throughout the script to test intermediate results, don't hesitate to use them. Also, think about updating the mail adress and don't forget that setTrashed can be manually reversed ;-) (better so when trying new code)

我今天早上花了一些时间来测试脚本,它有几个近似值" ;-) 这是一个干净"的版本,效果很好

EDIT : I took some time this morning to test the script, it had a couple of "approximations";-) here is a "clean" version that works nicely

function DeleteMyOldAvi() {
    var pageSize = 200;
    var files = null;
    var token = null;
    var i = null;
    var totalFiles = []
    var toDelete = []
    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('.avi')=='.avi'){
              totalFiles.push([files[n].getName(),files[n].getDateCreated().getTime(),files[n].getId()]);// store name, Date created in mSec, ID in a subarray
//            Logger.log(files[n].getName()+' created on '+Utilities.formatDate(files[n].getDateCreated(), 'GMT','MMM-dd-yyyy'))
            }
          }    
     } while (files.length == pageSize);// continue until job is done

     totalFiles.sort(function(x,y){ // sort array on milliseconds date created (numeric/descending)
                var xp = x[1];
                var yp = y[1];
                return yp-xp ;
                 });
//     Logger.log(totalFiles.length)

       if(totalFiles.length>100){

        for(nn=totalFiles.length-1;nn>=100;nn--){
          toDelete.push(totalFiles[nn]) ;// store the files to delete
           }
//       Logger.log(toDelete)

        for(n=0;n<toDelete.length;++n){
          var file = toDelete[n]
          DocsList.getFileById(file[2]).setTrashed(true);// move to trash each file that is in the toDelete array
          Logger.log(file[0]+' was deleted');// log the file name to create mail message
          }
          MailApp.sendEmail('myMail@gmail.com', 'Script AUTODELETE report', Logger.getLog());// send yourself a mail
       }else{
          MailApp.sendEmail('myMail@gmail.com', 'Script AUTODELETE report', 'No file deleted');// send yourself a mail
       }
 }