【问题标题】:Google Apps Script to delete all files from google drive?谷歌应用脚​​本从谷歌驱动器中删除所有文件?
【发布时间】:2013-10-27 04:19:36
【问题描述】:

我需要从我的驱动器中删除所有超过 16 GB 的文件,并且我需要花费数小时手动删除。

寻求支持谷歌的帮助,但没有任何帮助。

我可以移动我执行的 Google Apps 脚本吗?

【问题讨论】:

    标签: google-apps-script google-drive-api


    【解决方案1】:

    我假设您已经熟悉 Google Apps 脚本,知道如何在驱动器中创建脚本、管理编辑器等...如果您不熟悉,请从这里开始https://developers.google.com/apps-script/overview

    这里有一个小脚本会列出你所有的文件并将它们设置为垃圾箱,你仍然需要去垃圾箱并永远删除。

    使用此脚本时要小心:将所有文件移至垃圾箱

    您需要在运行时取消对 file.setTrashed(true) 的注释

    function processAllFiles() {
      // we look for the continuation token from the UserProperties
      // this is useful as the script may take more that 5 minutes 
      // (exceed execution time)
      var continuationToken = UserProperties.getProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN');
    
      if (continuationToken == null) {
        // firt time execution, get all files from drive
        var files = DriveApp.getFiles();
        // get the token and store it in a user property
        var continuationToken = files.getContinuationToken();
        UserProperties.setProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN', continuationToken);
      } else {
        // we continue to execute (and move everything to trash)
        var files = DriveApp.continueFileIterator(continuationToken);
      }
    
       while (files.hasNext()) {
         var file = files.next();
    //     file.setTrashed(true);
         Logger.log(file.getName());
      }
    
      // finish processing delete the token
      UserProperties.deleteProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN');
    }
    

    您可能会留下很多文件夹(如果它们是出于某种原因以编程方式创建的 ;)),因此您可以运行这个小脚本将它们移动到垃圾箱中。不要忘记取消注释下面计数的行。

    function processAllFolder() {
    // Log the name of every folder in the user's Drive.
      var folders = DriveApp.getFolders();
      while (folders.hasNext()) {
        var folder = folders.next();
         Logger.log(folder.getName());
         // folder.setTrashed(true);
      }
    };
    

    让我知道你的效果如何。

    【讨论】:

    • 感谢文件夹更新(以及评论:-)(+1upvote)
    • 当取消注释包含 setTrashed() 的行时,这会不断生成服务器错误。我怀疑这与删除自身的脚本文件有关,但@Sergeinsas 的回答也会在该行生成服务器错误。
    • 对我来说开箱即用(它为我节省了一整天的工作时间 - 我有大约 50GB 需要删除)。
    • 嗯,我明白了:找不到具有给定 ID 的项目,或者您无权访问它。 (第 20 行,文件“代码”)。第 20 行是:file.setTrashed(true);有什么问题?
    • 会不会是您不是您要删除的文件的所有者?
    【解决方案2】:

    我对 patt0 的(最佳)答案非常感兴趣,并尝试通过添加一些功能来改进它(只是一点点 :-) 以使我个人舒适......

    这是我来的,只是为了提供信息(添加的数据记录保存在一个不会被删除的文档中,这样你就可以跟踪发生了什么 - 或者如果你运行它会发生什么已评论 setTrashed()- 并向您发送带有日志数据文档 url 的邮件以便于访问)

    function processAllFiles() {
      var continuationToken = UserProperties.getProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN');
      var numberOfFiles = Number(UserProperties.getProperty('Number_of_files_processed'));
      var thisScriptFileId = DocsList.find("continuationToken = UserProperties.getProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN')")[0].getId();
      Logger.log(thisScriptFileId);
      if(UserProperties.getProperty('logFileId') == null ){
        var logFileId = DocumentApp.create('Delete All Files Log data').getId();
        var doc = DocumentApp.openById(logFileId);
        doc.getBody().appendParagraph('List of all the files you deleted\n\n');
        UserProperties.setProperty('logFileId', logFileId);
      }
      if (continuationToken == null) {
        var files = DriveApp.getFiles();
        var continuationToken = files.getContinuationToken();
        UserProperties.setProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN', continuationToken);
        UserProperties.setProperty('Number_of_files_processed', '0');
      } else {
        var files = DriveApp.continueFileIterator(continuationToken);
      }
    
       while (files.hasNext()) {
         var file = files.next();
         if(file.getId()!=logFileId&&file.getId()!=thisScriptFileId){
    //     file.setTrashed(true);
           numberOfFiles++
             Logger.log('File '+Utilities.formatString("%05d", numberOfFiles)+' : '+file.getName());
         }
       }
      var paragraphStyle = {};
      paragraphStyle[DocumentApp.Attribute.FONT_SIZE] = 8 ;
    
      var doc = DocumentApp.openById(UserProperties.getProperty('logFileId'));
      doc.getBody().appendParagraph(Logger.getLog()).setAttributes(paragraphStyle);
      MailApp.sendEmail(Session.getEffectiveUser().getEmail(),'DeleteFiles result Log','Here is the log data to your script :\n\n'
                        +doc.getUrl()+'\n\nExecuted by this script : '+DocsList.getFileById(thisScriptFileId).getUrl());
      // finish processing delete the token
      UserProperties.deleteProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN');
      UserProperties.deleteProperty('Number_of_files_processed');
    }
    

    【讨论】:

    • 记录 Serge 的好东西,我在基本版本中添加了一个处理文件夹的功能...
    • 很棒的员工,在这里运行了 2 个脚本并删除了所有文件。并且仍然生成删除文件的日志!也非常感谢。
    • 很高兴它有帮助,这很有趣:-)
    • 您的员工为您服务;)
    【解决方案3】:

    结合patt0Serge insas 的出色工作以及关于永久删除的Sandy Good's answer,我将分享我自己的这个脚本的最终版本。

    首先,确保按照Sandy Good的回答中的说明进行操作,没有它,脚本将无法永久删除 文件(您仍然可以将文件丢弃)。

    脚本特点:

    • Stackdriver 日志记录 - 每处理 50 个文件,就会有一条日志消息与状态有关。
      我建议将 severity!=ERROR 添加到过滤器中,同时跟踪进度。
    • 出错时跳过 - 有些文件无法删除(最常见的是与您共享的文件,但您不拥有这些文件,因此无权删除),这些文件会被记录下来。
    • 继续
      script.google.com 上的脚本运行时间不得超过 30 分钟。
      当此脚本失败/超时时,您将能够运行它再次,它将从停止的地方继续。

    这个脚本不能做什么:

    • 未触及第三方应用程序数据,仍需要手动删除。 (占用空间的应用程序的一个很好的例子:WhatsApp backup

    危险区域

    此脚本将在其必须运行的分配时间内删除它可以删除的所有内容,因为我已经注释掉了文件的实际删除/垃圾(与其他答案相同)。
    要实际执行删除/垃圾处理,请取消注释相关行。

    祝你好运。
    - 著名的遗言

    代码

    也可通过此直接链接获得:(https://lksz.me/GoogleDriveCleaner)

        // dont-delete-me-secret-code-1Nq0feuBuyGy5KWGqzEnvXODWx519Ka1aNSlXF_Bg6q1yP
        // Link to this script: https://lksz.me/GoogleDriveCleaner
        // Script based on the StackOverflow answers at:
        //      https://stackoverflow.com/a/25750738
        // and  https://stackoverflow.com/a/19616656 and https://stackoverflow.com/a/19615407
        //
        // You might need to run processAllFiles() multiple times.
        // To start from scratch, first run clearContinuationToken()
        //
        // Last modified Nov 22, 2018
        //
        function processAllFiles() {
          var usrP = PropertiesService.getUserProperties();
    
          var continuationToken = usrP.getProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN');
          var numberOfFiles = Number(usrP.getProperty('Number_of_files_processed'));
          var numberOfErrors = Number(usrP.getProperty('Number_of_files_failed'));
    
          var thisScriptFileId = DriveApp
                .searchFiles('fullText contains "// dont-delete-me-secret-code-1Nq0feuBuyGy5KWGqzEnvXODWx519Ka1aNSlXF_Bg6q1yP"')
                .next()
                .getId();
    
          Logger.log("thisScriptFileId = " + thisScriptFileId);
          if (continuationToken == null) {
            var files = DriveApp.getFiles();
            var continuationToken = files.getContinuationToken();
            usrP.setProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN', continuationToken);
            usrP.setProperty('Number_of_files_processed', '0');
            usrP.setProperty('Number_of_files_failed', '0');
          } else {
            var files = DriveApp.continueFileIterator(continuationToken);
          }
    
          while (files.hasNext()) {
            var file = files.next();
            var fileID = file.getId();
            if(fileID!=thisScriptFileId){
              try {
                // Log advancement
                if( 1 == (numberOfErrors + numberOfFiles) % 50 ) {
                  var msg = Utilities.formatString("%05d", numberOfFiles + numberOfErrors) + ', next file is: ' + file.getName();
    
                  console.log({message: msg, numberOfFiles: numberOfFiles, numberOfErrors: numberOfErrors, total: numberOfFiles + numberOfErrors });
                  Logger.log(msg);
    
                  usrP.setProperty('Number_of_files_processed', numberOfFiles);
                  usrP.setProperty('Number_of_files_failed', numberOfErrors);
                }
    
                // Un-comment one of the options below.
                // Option 1: Permanent removal
                // Follow instructions in https://stackoverflow.com/a/25750738 to enable Drive API
                // Drive.Files.remove(fileID);
    
                // Option 2: Trash file, will need to empty trash after script runs.
                // file.setTrashed(true);
    
                numberOfFiles++;
              } catch (e) {
                numberOfErrors++;
                var msg = Utilities.formatString("%05d", numberOfFiles + numberOfErrors) + ', failed to remove file: ' + file.getName();
    
                console.error({message: msg, numberOfFiles: numberOfFiles, numberOfErrors: numberOfErrors, total: numberOfFiles + numberOfErrors });
                Logger.log(msg);
              }
            }
          }
    
          // finish processing delete the token
          clearContinuationToken();
        }
    
        function clearContinuationToken() {
          var usrP = PropertiesService.getUserProperties();
          usrP.deleteProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN');
          usrP.deleteProperty('Number_of_files_processed');
          usrP.deleteProperty('Number_of_files_failed');
          console.log({message: 'clearContinuationToken - Logging test', values: 1, testing: "bubu"});
        }
    
        function processAllFolder() {
          // Log the name of every folder in the user's Drive.
          var folders = DriveApp.getFolders();
          while (folders.hasNext()) {
            var folder = folders.next();
            console.log(folder.getName());
            // folder.setTrashed(true);
          }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 2020-03-13
      • 2016-06-22
      • 2013-01-15
      • 1970-01-01
      • 2018-03-21
      相关资源
      最近更新 更多