Google Apps 脚本触发器 - 每当将新文件添加到文件夹时运行

And*_*ndy 5 triggers google-apps-script google-drive-api

每当将新文件添加到特定文件夹时,我想执行谷歌应用程序脚本。

\n

目前我正在使用每 x 分钟运行一次的时钟触发器,但我只需要在向文件夹添加文件时运行脚本。有没有办法做到这一点?

\n

与这个问题相同- 现在已经快 3 岁了。问题下面的评论指出:

\n
\n

如果这就是你所希望的,那么就没有触发因素。\n东西是如何进入文件夹的,您对此有任何控制权吗?\n\xe2\x80\x93 Jesse Scherer 2018 年 4 月 8 日 3:02

\n
\n

我想知道这个评论是否仍然有效,如果有效,那么是否有解决方法。

\n

soM*_*rio 11

问题:

不幸的是,您读到的评论仍然是正确的这是所有可用触发器列表,a 的触发器new file added to a folder不是其中之一。

解决方法/说明:

我可以为您提供一种解决方法,开发人员在构建附加组件时通常会使用该方法。您可以利用PropertiesService类。逻辑很简单。

  1. 您将存储脚本范围内的键值对:

在您的情况下,键将是文件夹 ID,值将是该文件夹下的文件数。

  1. 您将设置一个时间驱动的mainFunction触发器,例如每一分钟执行一次。

  2. 该脚本将计算所选文件夹中当前文件的数量。负责该功能的函数是countFiles.

  3. checkProperty函数负责检查该文件夹下当前的文件数量是否与旧的文件数量相匹配。如果存在匹配,意味着没有添加文件,则checkProperty返回false,否则返回true并更新当前文件夹 ID 的属性,因此当脚本在 1 分钟后运行时,它将与新值进行比较。

  4. 如果checkProperty返回true,则执行所需的代码。

代码片段:

设置时间驱动的触发器mainFunctionif(runCode)如果语句中的文件数量发生变化,则无论您在语句括号内放入的任何代码都将被执行folderID

function mainFunction(){
  const folderID = 'folderID'; //provide here the ID of the folder
  const newCounter = countFiles(folderID);
  const runCode = checkProperty(folderID, newCounter);
  
  if(runCode){
   // here execute your main code
   // 
    console.log("I am executed!");
   //
  }
}
Run Code Online (Sandbox Code Playgroud)

以下是需要位于同一项目中的辅助函数(您可以将它们放在同一脚本或不同脚本中,但位于同一“脚本编辑器”中)。

function countFiles(folderID) {
  const theFolder = DriveApp.getFolderById(folderID);
  const files = theFolder.getFiles();
  let count = 0;
  while (files.hasNext()) {
   let file = files.next();
   count++;
   };
  return count;
}


function checkProperty(folderID, newC){
  const scriptProperties = PropertiesService.getScriptProperties();
  const oldCounter = scriptProperties.getProperty(folderID);
  const newCounter = newC.toString();
  if(oldCounter){
    if(oldCounter==newCounter){
      return false;
    }
    else{
      scriptProperties.setProperty(folderID, newCounter);  
      return true;
    }
  }
  else{
     scriptProperties.setProperty(folderID, newCounter);  
     return true;
  }
}
Run Code Online (Sandbox Code Playgroud)