无法通过Drive Service API或DriveApp复制Apps Script文件
解决Google Apps Script无法复制Apps Script文件的问题
问题原因
- 你最初使用的
DriveApp.File.makeCopy()方法不支持复制Google Apps Script文件(MIME类型为application/vnd.google-apps.script),这类属于特殊的Google Workspace容器文件,必须通过Drive API并配合特定参数才能复制。 - 你第二个Drive API脚本的核心问题是缺少复制Apps Script文件的必要参数,导致权限校验失败。
修正方案
1. 确保启用Drive API
在AppScript编辑器中:
- 点击左侧菜单栏的「服务」→「添加服务」
- 选择「Drive API」并添加(版本选v2即可)
2. 修正后的递归复制脚本
以下脚本会递归复制文件夹中的所有文件(包括Apps Script文件)和子文件夹:
const copyFolderRecursively = (sourceFolderId, targetFolderId) => { // 复制当前文件夹下的所有非文件夹文件 const fileQueryParams = { q: `'${sourceFolderId}' in parents and trashed = false and mimeType != 'application/vnd.google-apps.folder'`, supportsAllDrives: true, includeItemsFromAllDrives: true, fields: 'items(id, title, mimeType)' }; const files = Drive.Files.list(fileQueryParams).items; if (files) { files.forEach(file => { const copyResource = { title: file.title, parents: [{ id: targetFolderId }] }; // 关键:添加copyRequiresWriterPermission参数以支持Apps Script文件复制 const copyOptions = { supportsAllDrives: true, copyRequiresWriterPermission: true }; Drive.Files.copy(copyResource, file.id, copyOptions); }); } // 递归处理子文件夹 const folderQueryParams = { q: `'${sourceFolderId}' in parents and trashed = false and mimeType = 'application/vnd.google-apps.folder'`, supportsAllDrives: true, includeItemsFromAllDrives: true, fields: 'items(id, title)' }; const folders = Drive.Files.list(folderQueryParams).items; if (folders) { folders.forEach(folder => { // 创建目标子文件夹 const newFolderResource = { title: folder.title, parents: [{ id: targetFolderId }] }; const newFolder = Drive.Files.insert(newFolderResource, null, { supportsAllDrives: true }); // 递归复制子文件夹内容 copyFolderRecursively(folder.id, newFolder.id); }); } };
3. 关键注意事项
copyRequiresWriterPermission: true:这是复制Apps Script文件的核心参数,因为这类文件默认要求写入权限才能复制,添加该参数后会允许符合权限条件的账号完成复制。- 权限校验:运行脚本的账号必须对源文件夹/文件和目标文件夹拥有编辑权限;如果源文件在共享驱动器中,需确保账号有该驱动器的操作权限。
- 字段指定:脚本中添加了
fields参数,只请求需要的字段,提升API调用效率。
内容的提问来源于stack exchange,提问作者fitMath
相关产品推荐
相关产品推荐

