基本上这个问题给出了我想做的事情的答案:
Google script to create a folder and then create a Google Doc in that folder
但它已经 5 年了,我想知道现在是否有更简单的方法。就我而言,我有很多现有文件夹,我想通过每隔一段时间运行的脚本在每个文件夹中创建一个特定文件。
谢谢。
编辑:
好的,当文件夹“test folder”位于共享驱动器中时,下面的代码可以正常工作(在答案中使用修改后的示例脚本 1)。
function testFunction() {
const notesFileName = 'test doc';
const folderName = 'test folder';
const query = "title = '" + folderName + "'";
// Find all folders that match the query.
var folders = DriveApp.searchFolders(query);
while (folders.hasNext()) {
// In all the sub-folders, of each found folder, create a file with the same name.
var folder = folders.next();
Logger.log("Found a folder: " + folder);
var subFolders = folder.getFolders();
while( subFolders.hasNext() ) {
var subFolder = subFolders.next();
Logger.log('Folder id: ' + subFolder.getId());
const doc = Drive.Files.insert({title: notesFileName, mimeType: MimeType.GOOGLE_DOCS, parents: [{id: subFolder.getId()}]}, null, {supportsAllDrives: true});
}
}
}
答案 0 :(得分:1)
我相信你的目标如下。
在这种情况下,我想建议使用 Drive API 创建新的 Google 文档。当使用 Drive API 时,可以在异步过程中运行到每个文件夹的 Google 文档的创建。示例脚本如下。
在使用此脚本之前,please enable Drive API at Advanced Google services。在此示例脚本中,新的 Google 文档会循环创建到特定文件夹中。
function sample1() {
const titleOfDocument = "sample document";
const folderIds = ["### folder ID1 ###", "### folder ID 2 ###",,,];
const documentIds = folderIds.map(id => Drive.Files.insert({title: titleOfDocument, mimeType: MimeType.GOOGLE_DOCS, parents: [{id: id}]}).id);
console.log(documentIds)
}
在使用此脚本之前,please enable Drive API at Advanced Google services。在此示例脚本中,使用 Google Apps 脚本库使用 Drive API 的批处理请求将新的 Google 文档创建到特定文件夹。这样,任务就以异步进程运行。
请安装 Google Apps 脚本库以使用批处理请求。 Ref
function sample2() {
const titleOfDocument = "sample document";
const folderIds = ["### folder ID1 ###", "### folder ID 2 ###",,,];
const requests = {
batchPath: "batch/drive/v3",
requests: folderIds.map(id => ({
method: "POST",
endpoint: `https://www.googleapis.com/drive/v3/files`,
requestBody: {name: titleOfDocument, mimeType: MimeType.GOOGLE_DOCS, parents: [id]},
})),
accessToken: ScriptApp.getOAuthToken(),
};
const result = BatchRequest.EDo(requests); // Using GAS library
const documentIds = result.map(({id}) => id);
console.log(documentIds)
}
对于上述示例脚本,如果您想检索特定文件夹下的文件夹 ID,您也可以使用 folderIds
如下。
const topFolderId = "### top folder ID ###";
const folders = DriveApp.getFolderById(topFolderId).getFolders();
const folderIds = [];
while (folders.hasNext()) {
folderIds.push(folders.next().getId());
}
顺便说一下,在当前阶段,为了移动文件,可以使用moveTo(destination)。使用这个,this 的脚本可以修改如下。
function createDoc(folderID, name) {
var folder = DriveApp.getFolderById(folderID);
var doc = DocumentApp.create(name);
DriveApp.getFileById(doc.getId()).moveTo(folder);
return doc;
}