google-apps-script - 如何使用 Google Apps 脚本 (GAS) 创建多个驱动器文件夹
问题描述
目标: 使用 GAS 创建多个文件夹(~100)。
问题 1:
使用带DriveApp.createFolder
ref的循环可以完成这项工作,但执行需要很长时间。我做了一些测量,创建 1 个文件夹大约需要 0.8 秒,即 100 个文件夹需要 80 秒!这是不切实际的。
for(let i=0;i<10;i++){
let folderID = DriveApp.createFolder('myfolder'+i.toString());
Logger.log(folderID);
}
问题2:
使用Advanced Drive Service或许可以完成这项工作,但我不知道如何Drive.Files.insert()
批量运行。多亏了Tanaike 的教程,我才设法创建了一个文件夹。下面的示例代码
function CreateFolder() {
let fileMetadata = {
'title': 'myDriveService',
'mimeType': 'application/vnd.google-apps.folder',
'parents': [{
'id': '{parent_folder_ID}'
}]
};
let respond = Drive.Files.insert(fileMetadata);
Logger.log(respond);
}
解决方案
我相信你的目标如下。
- 您想使用 Google Apps 脚本创建多重文件夹。
- 您希望为此降低流程成本。
为此,这个答案怎么样?
修改点:
在我的回答中,作为一种解决方法,我想建议针对您的情况使用批处理请求。批量请求以异步进程运行,一次 API 调用可运行 100 个请求。由此,认为可以降低处理成本。在这里,为了将批处理请求与简单脚本一起使用,使用了 Google Apps 脚本库。
该文件夹是使用 Drive API v3 中的 files.create 方法创建的。
用法:
1. 安装 Google Apps 脚本库。
要使用此示例脚本,请安装BatchRequest的 Google Apps 脚本库。您可以在https://github.com/tanaikech/BatchRequest#how-to-install查看安装库的方法。
2. 运行示例脚本。
请复制并粘贴以下脚本。请在 Advanced Google services中启用 Drive API。
function myFunction() {
let batchReqs = [];
for (let i = 0; i < 10; i++) {
batchReqs.push({
method: "POST",
endpoint: "https://www.googleapis.com/drive/v3/files",
requestBody: {name: 'myfolder'+i.toString(), mimeType: MimeType.FOLDER}
});
}
// Run batch requests using the library.
const limit = 100;
const split = Math.ceil(batchReqs.length / limit);
let folderIds = [];
for (let i = 0; i < split; i++) {
const res = BatchRequest.Do({batchPath: "batch/drive/v3", requests: batchReqs.splice(0, limit)});
const ids = res.getContentText().match(/{[\s\S]+?}/g).map(function(e) {return JSON.parse(e).id});
folderIds = folderIds.concat(ids);
}
console.log(folderIds)
}
- 当您运行 的函数时
myFunction
,在这种情况下,在根文件夹中创建了 10 个文件夹。 - 在此示例脚本中,即使
i < 10
for 循环的次数超过 100,脚本也会通过拆分每 100 个请求来工作。
笔记:
- 请将此脚本与 V8 一起使用。
参考:
推荐阅读
- java - 将 Kafka Connect JDBC Source Connector 输出转换为自定义格式
- kubernetes - 使用 podAffinity 和 podAntiaffinity 时验证 matchExpression 时出错
- java - 使用 lombok builder 获取字段值
- cmake - 预编译 googletest 以在裸机上运行
- r - mcar_test 的外部函数调用 (arg 2) 中的 NA/NaN/Inf 错误
- android - TextView 中的粗体文本不适用于 Spanned 和 String 的组合
- python - 让 pandas.read_csv 处理 .txt 第一列中的空格
- java - 页面项目的倒计时计时器 oracle apex
- node.js - 中间件 next() routeHandler
- java - 合并间隔的二维数组