首页 > 解决方案 > 如何在 Google Apps 脚本中使用全局变量?

问题描述

我是 Google Apps 脚本的新手。我定义了函数来获取文件夹中locate_file每个文件的名称。New York Bike ShareDriveApp.getFolderById

let folder
let file

function locate_file() {
  folder = DriveApp.getFolderById("162jksCkY98VeQAgnHeAzmnCVbGRKg9rd")
  .getFiles()
  
  while (folder.hasNext())  {
    file = folder.next().getName()

    console.log(file)
  }
}

上面的代码在执行日志中返回以下结果:

10:47:07 AM Info    201906-citibike-tripdata.csv
10:47:07 AM Info    201905-citibike-tripdata.csv
10:47:07 AM Info    201904-citibike-tripdata.csv
10:47:07 AM Info    201903-citibike-tripdata.csv
10:47:07 AM Info    201902-citibike-tripdata.csv
10:47:07 AM Info    201901-citibike-tripdata.csv
10:47:08 AM Notice  Execution completed

由于我已经定义了 global variable folder,我计划在另一个函数中重用该变量。下面的函数仅用于演示目的,打印出存储在folder变量中的文件名。它失败了。

function check_files()  {
  while (folder.hasNext())  {
    file = folder.next().getName()

    console.log(file)
  }
}
10:53:44 AM Notice  Execution started
10:53:45 AM Error   TypeError: Cannot read property 'hasNext' of undefined
                    check_files @ Code.gs:16

感谢你的帮助。

标签: google-apps-scriptglobal-variables

解决方案


如果要使用文件夹作为全局变量,在这种情况下,我建议使用文件夹 ID 作为全局变量。因为folderfolder = DriveApp.getFolderById("###").getFiles()文件夹迭代器。为此,我认为可以使用 PropertiesService。当这反映到 Google Apps Script 时,它变成如下。

示例脚本:

// At first, please run this function. By this, the value of "folderId" is stored to PropertiesService.
function setGlobalVariable() {
  const folderId = "162jksCkY98VeQAgnHeAzmnCVbGRKg9rd";
  PropertiesService.getScriptProperties().setProperty("folderId", folderId);
}

// As the next step, please run this function. By this, "folderId" is retrieved from PropertiesService and it is used.
function check_files() {
  const folderId = PropertiesService.getScriptProperties().getProperty("folderId");
  if (folderId) {
    const folder = DriveApp.getFolderById(folderId).getFiles();
    while (folder.hasNext())  {
      file = folder.next().getName();
      console.log(file);
    }
  } else {
    throw new Error("No folder ID.");
  }
}
  • 首先,请运行setGlobalVariable()。由此,“folderId”的值被存储到PropertiesService。并且,作为下一步,请运行check_files(). 由此,从PropertiesService 中检索“folderId”并使用它。

  • 如果要更改文件夹ID,请修改setGlobalVariable()并再次运行。

参考:


推荐阅读