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

Google Apps Script如何遍历所有层级子文件夹并批量重命名文件?

问题解答:Google Apps Script 递归处理文件夹及文件重命名

1. 获取指定文件夹下所有层级的子文件夹

要遍历所有深度的子文件夹,最直接的方式是用递归函数——让函数自己调用自己,逐层处理每一级子文件夹。这里给你一个可直接用的示例脚本:

function getAllFolders(rootFolderId) {
  // 用来存放所有文件夹的数组
  const allFolders = [];
  // 获取根文件夹对象
  const rootFolder = DriveApp.getFolderById(rootFolderId);
  
  // 定义递归遍历的内部函数
  function traverseFolder(folder) {
    // 把当前文件夹加入结果数组
    allFolders.push(folder);
    // 获取当前文件夹的所有子文件夹
    const subFolders = folder.getFolders();
    // 遍历每个子文件夹,递归调用自身继续处理
    while (subFolders.hasNext()) {
      traverseFolder(subFolders.next());
    }
  }
  
  // 启动递归遍历
  traverseFolder(rootFolder);
  // 返回所有文件夹(如果只需要ID,可改成 folder.getId() 提取)
  return allFolders;
}

调用示例:

const allFolders = getAllFolders("你的根文件夹ID");
// 打印所有文件夹的名称和ID
allFolders.forEach(folder => {
  Logger.log(`文件夹: ${folder.getName()} | ID: ${folder.getId()}`);
});

2. 递归重命名指定文件夹及所有子文件夹中的文件

你的现有脚本已经能处理单个文件夹的文件,只需要给它加上递归遍历子文件夹的逻辑就行。我把你的代码拆分成两个函数,让结构更清晰,同时实现递归处理:

function renameFilesInFolderAndSubfolders(folderID) { 
  const targetFolder = DriveApp.getFolderById(folderID);
  
  // 先处理当前文件夹内的文件
  renameFilesInSingleFolder(targetFolder);
  
  // 递归处理所有子文件夹
  const subFolders = targetFolder.getFolders();
  while(subFolders.hasNext()){
    const subFolder = subFolders.next();
    // 调用自身,继续处理子文件夹
    renameFilesInFolderAndSubfolders(subFolder.getId());
  }
}

// 提取你原有的单文件夹重命名逻辑为独立函数
function renameFilesInSingleFolder(folder) {
  const files = folder.getFiles();
  while(files.hasNext()){ 
    const file = files.next();
    const oldFileName = file.getName();
    const checkIfMatch = oldFileName.substring(oldFileName.length - 3);
    let newFileName = "";
    
    if (checkIfMatch === "OBS"){ 
      newFileName = oldFileName;
    } else { 
      newFileName = oldFileName + "_OBS";
    }
    
    file.setName(newFileName);
    Logger.log(`已重命名: ${oldFileName} → ${newFileName}`);
  }
}

使用说明:

  • 直接调用 renameFilesInFolderAndSubfolders("你的根文件夹ID"),就能自动处理该文件夹及其所有子文件夹里的文件。
  • 拆分函数是为了让逻辑更清晰:renameFilesInSingleFolder 专注处理单文件夹的文件重命名,renameFilesInFolderAndSubfolders 负责遍历所有层级的文件夹并调用重命名函数。
  • 如果你的文件数量极多或者文件夹层级过深,可能会触发Google Apps Script的6分钟执行时间限制,这种情况可以考虑分批处理,不过一般中小规模的场景这个脚本完全够用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:23:47