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

如何修正Google Apps Script获取Google Drive共享盘文件根文件夹路径的问题?

修复共享盘文件路径根显示为「Drive」的问题

你的Google Apps Script在处理共享盘中的文件时,会将根目录显示为「Drive」而非共享盘实际名称,这是因为DriveApp对共享盘根容器的默认处理逻辑导致的。以下是修复后的代码:

function getFolderPath() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const dataRange = sheet.getDataRange();
  const values = dataRange.getValues();
  const docIdCol = 3; // 文档ID列(C列)
  const folderPathCol = docIdCol + 1; // 路径输出列(D列)
  
  // 插入路径列并设置表头
  sheet.insertColumnBefore(folderPathCol);
  sheet.getRange(1, folderPathCol).setValue("Folder Path");
  
  // 遍历每行处理文档ID
  for (let i = 1; i < values.length; i++) {
    const docId = values[i][docIdCol - 1];
    let folderPath = "";
    try {
      const file = DriveApp.getFileById(docId);
      let currentFolder = file.getParents().next();
      
      // 向上遍历父文件夹链
      while (true) {
        folderPath = `${currentFolder.getName()}/${folderPath}`;
        const parentFolders = currentFolder.getParents();
        
        if (!parentFolders.hasNext()) {
          // 处理顶层目录:区分共享盘和普通驱动器
          if (currentFolder.isSharedDrive()) {
            // 用共享盘名称替换路径开头的「Drive」
            const driveName = currentFolder.getDrive().getName();
            folderPath = `${driveName}/${folderPath.slice(currentFolder.getName().length + 1)}`;
          } else if (currentFolder.getName() === "Drive") {
            // 普通「我的驱动器」替换为实际名称
            folderPath = `My Drive/${folderPath.slice(6)}`;
          }
          break;
        }
        currentFolder = parentFolders.next();
      }
      
      // 移除末尾多余斜杠
      folderPath = folderPath.replace(/\/$/, "");
      sheet.getRange(i + 1, folderPathCol).setValue(folderPath);
    } catch (e) {
      sheet.getRange(i + 1, folderPathCol).setValue(`获取失败:${e.message}`);
    }
  }
}

核心修复点:

  • 共享盘根目录识别:通过isSharedDrive()判断当前顶层文件夹是否属于共享盘,调用getDrive().getName()获取共享盘真实名称,替换路径中错误的「Drive」
  • 路径初始化:确保folderPath初始为空,避免拼接时出现undefined
  • 普通驱动器兼容:将普通我的驱动器的「Drive」替换为「My Drive」(可根据需求修改)
  • 错误信息优化:捕获异常时显示具体错误,便于排查权限或ID无效问题

注意:若脚本无法访问共享盘,需在脚本编辑器的「扩展」→「Apps Script 编辑器」→「服务」中启用Drive API,并确保当前账号拥有共享盘的访问权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 11:27:46