【问题标题】:How to write Google Sheets Script to automatically delete files not owned me如何编写 Google 表格脚本以自动删除不属于我的文件
【发布时间】:2019-02-14 16:28:14
【问题描述】:

我有一个表格表单,我们的公司用户将它保存到我们的公司 google Drive 文件夹 (G Suite)。我们需要将这些表格保留 30 天。

我想在 35 天后自动删除这些文件。所以我写了这个脚本:

function DeleteOldFiles() {
  var Folders = new Array(
    '0B8xnkPYxGFbUMktOWm14TVA3Yjg',      
   '1C_VUaqPl9FQlaajY_wsZzJgVGHDrPKm8');
  var Files;

  Logger.clear();

  for each (var FolderID in Folders) {
    Folder = DriveApp.getFolderById(FolderID)
    Files = Folder.getFiles();

    while (Files.hasNext()) {
      var File = Files.next();

      if (new Date() - File.getLastUpdated() > 35 * 24 * 60 * 60 * 1000) {
       File.setTrashed(true); // Places the file int the Trash folder
      //  Drive.Files.remove(File.getId()); // Permanently deletes the file
        Logger.log('File ' + File.getName() + ' was deleted.');
      }}}

  if(Logger.getLog() != '')
    MailApp.sendEmail('batnip@choiceaviation.com', 'Backups have been removed from Google Drive', Logger.getLog());}

问题是我有时会收到这些消息: “拒绝访问:DriveApp。(第 18 行,文件“代码”)”

脚本有时有效,有时无效。我最终得出的结论是,它可能仅在删除我自己的文件时才有效,但在其他 G Suite 用户那里有文件时无效。

解决方案?

【问题讨论】:

标签: google-apps-script google-sheets google-drive-api delete-file


【解决方案1】:

你是对的,only the owner may validly use the .setTrashed 函数。您可以先尝试将自己设置为所有者,使用 .setOwner(email address):

if (new Date() - File.getLastUpdated() > 35 * 24 * 60 * 60 * 1000) {
   File.setOwner('your email address'); // Transfers ownership to user
   File.setTrashed(true); // Places the file int the Trash folder
  //  Drive.Files.remove(File.getId()); // Permanently deletes the file
    Logger.log('File ' + File.getName() + ' was deleted.');
  }}}

如果这不起作用 - 我相信它需要域管理员权限 - 您也可以尝试创建一个存档文件夹作为解决方法,然后简单地将文件移动到其中,如下所述:stackoverflow.com/questions/38808875/moving-files-in-google-drive-using-google-script

【讨论】:

  • 感谢您的评论。 'File.setOwner' 不起作用。 (我不知道为什么,因为我是公司的超级管理员(Gsuite 所有者)。关于如何更改此设置的任何想法?
【解决方案2】:

解决此问题的适当工具是 Google 共享驱动器。但如果这在您的情况下不起作用,您可以创建自己的垃圾文件夹(例如“ToTrash”)。然后授予可以垃圾的人对该文件夹的权限。你让人们使用将文件移动到你自己的“ToTrash”文件夹的脚本而不是垃圾。有时您会删除“ToTrash”文件夹中的所有文件。为此,您还可以编写一个自动触发的脚本,例如每天一次。

/* TRASHFOLDERID is the Id of your own created trash folder.
/* assuming that file is a file object you constructed
/* by getting it by id, name, or FileIterator
const trashFolder = DriveApp.getFolderById(TRASHFOLDERID);
file.moveTo(trashFolder);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多