google-apps-script - 如何在 Google Apps 脚本中使用全局变量?
问题描述
我是 Google Apps 脚本的新手。我定义了函数来获取文件夹中locate_file
每个文件的名称。New York Bike Share
DriveApp.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
感谢你的帮助。
解决方案
如果要使用文件夹作为全局变量,在这种情况下,我建议使用文件夹 ID 作为全局变量。因为folder
是folder = 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()
并再次运行。
参考:
推荐阅读
- google-cloud-dataflow - PubSub 到 Spanner 流管道
- sql - 不断收到错误 ')' 附近的语法不正确。(102) (SQLExecDirectW)
- docker - docker compose 如何在没有服务的情况下运行多个图像
- rabbitmq - RabbitMQ - 在最终放入死信队列之前重试最大次数
- soapui - Maximo Web 服务同步响应:messageid 的用途是什么?
- java - org.postgresql.util.PSQLException:错误:运算符不存在:整数 = bytea
- reactjs - 使用 Redux 的类组件
- windows - 我的一个驱动器未显示在此PC 列表中
- flutter - 我想加密 mp4 文件以防止共享文件。如何加密文件?
- c++ - 无法在列表向量中使用列表