You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过AppScript快速批量移动谷歌云端硬盘中的文件?

谷歌云端硬盘批量移动文件提速问题

问题描述

我需要将谷歌云端硬盘某文件夹中的数百个PDF文件移动到同一云端硬盘的另一个文件夹中。目前使用DriveApp的moveTo方法实现,代码如下:

for (var i=0; i<idList.length; i++){
DriveApp.getFileById(idList[i]).moveTo(destinationFolder);}

该方法虽能生效,但移动数百个文件时速度极慢。请问是否存在大幅提升移动速度的方法?

编辑(1)
针对@Tanaike的评论说明:为清晰起见已将fileList改为idList,idList存储了所有待移动文件的ID值。

编辑(2)
以下是基于Tanaike的答案编写的完整代码示例:

function main(){

const sourceFolderId = "1G7QNWc1vFTLAbOKdxN_3TiSVCU6962bh";
const destinationFolderId = "1hx7jtdlLQAhOWKgo4MUHgw8QuDWAdMyR";

var files = DriveApp.getFolderById(sourceFolderId).getFiles();
var idList = [];

while (files.hasNext()){
  file = files.next();
  idList.push(file.getId())
}

  const size = 100;
  const ar = [...Array(Math.ceil(idList.length / size))].map((_) => idList.splice(0, size));

  ar.forEach(ids => {
    const requests = ids.map(fileId => ({
      method: "PATCH",
      endpoint: `https://www.googleapis.com/drive/v3/files/${fileId}?supportsAllDrives=true&enforceSingleParent=true&addParents=${destinationFolderId}`,
      requestBody: {}
    }));
    const res = batchRequests_({ batchPath: "batch/drive/v3", requests });
    console.log(res.getContentText());
  });

  // DriveApp.createFile(); // This comment line is used for automatically detected a scope of Drive APi by the script editor. So, please don't remove this line
}

function batchRequests_(object) {
  const { batchPath, requests } = object;
  const boundary = "sampleBoundary12345";
  const lb = "\r\n";
  const payload = requests.reduce((r, e, i, a) => {
    r += `Content-Type: application/http${lb}`;
    r += `Content-ID: ${i + 1}${lb}${lb}`;
    r += `${e.method} ${e.endpoint}${lb}`;
    r += e.requestBody ? `Content-Type: application/json; charset=utf-8" ${lb}${lb}` : lb;
    r += e.requestBody ? `${JSON.stringify(e.requestBody)}${lb}` : "";
    r += `--${boundary}${i == a.length - 1 ? "--" : ""}${lb}`;
    return r;
  }, `--${boundary}${lb}`);
  const params = {
    muteHttpExceptions: true,
    method: "post",
    contentType: `multipart/mixed; boundary=${boundary}`,
    headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
    payload,
  };
  return UrlFetchApp.fetch(`https://www.googleapis.com/${batchPath}`, params);
}

运行时遇到如下错误:

Exception: UrlFetch calls to https://www.googleapis.com/batch/drive/v3 are not permitted by your admin

由于工作环境禁止UrlFetch调用,无法验证该脚本是否可行。


内容的提问来源于stack exchange,提问作者Chris Aung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 09:07:46