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

Google Apps Script复制Drive文件夹时从表格读取ID报错如何解决

问题排查与修正方案

你代码里存在2处核心错误:

  • 变量调用顺序错误:你在resSource、resTarget两个变量完成赋值之前,就提前调用了DriveApp.getFolderById(resSource)和DriveApp.getFolderById(resTarget),此时变量为未定义状态,自然会抛出ID异常。
  • toString方法调用格式错误:toString是函数方法,必须加括号执行才能返回字符串结果,你写的sourceText.toString实际是将函数本身赋值给了变量,而非返回转换后的字符串。

修正后的完整代码

function onOpen(){
  createMenu()
}
function createMenu (){
  const ui = SpreadsheetApp.getUi() 
  const menu = ui.createMenu("Copy Folders")
  menu.addItem("Copy Folder", "copyFolder")
  menu.addToUi()
}

/**
 * 将源文件夹内所有文件复制到目标文件夹
 */
function copyFolderContents_(source, target) {
  // 遍历源文件夹内的所有文件
  const filesIterator = source.getFiles()
  while (filesIterator.hasNext()) {
    const file = filesIterator.next()
    // 保留原文件名复制文件到目标文件夹
    file.makeCopy(file.getName(), target)
  }
}

/**
 * 递归复制文件夹及其所有子文件夹、文件
 */
function copyFolder_(toCopy, copyInto) {
  // 在目标路径下创建同名新文件夹
  const newFolder = copyInto.createFolder(toCopy.getName())
  // 复制文件夹内容
  copyFolderContents_(toCopy, newFolder)
  // 遍历所有子文件夹
  const foldersIterator = toCopy.getFolders()
  while (foldersIterator.hasNext()) {
    const folder = foldersIterator.next()
    // 递归调用复制子文件夹及其内容
    copyFolder_(folder, newFolder)
  }
}

/**
 * Google Apps Script UI触发入口函数
 */
function copyFolder() {
  // 先读取电子表格单元格内容,完成变量赋值
  const app = SpreadsheetApp
  const ss = app.getActiveSpreadsheet()
  const activeSheet = ss.getActiveSheet()
  const sourceText = activeSheet.getRange("A2").getValue()
  const resSource = sourceText.toString()
  console.log(resSource)
  const targetText = activeSheet.getRange("B2").getValue()
  const resTarget = targetText.toString()
  console.log(resTarget)

  // 变量赋值完成后再调用Drive接口获取文件夹对象
  const toCopy = DriveApp.getFolderById(resSource)
  const copyInto = DriveApp.getFolderById(resTarget)

  // 执行文件夹复制逻辑
  copyFolder_(toCopy, copyInto)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:54:05