Google Apps Script实现文件从父文件夹迁移至食品类月度子文件夹
自动迁移Google共享云端硬盘文件至对应月度子文件夹方案
核心逻辑
- 每月初执行脚本时,自动计算上个月的年月名称(比如9月跑脚本,目标是August 2022;10月跑则是September 2022)
- 遍历父文件夹里的所有文件,按文件名(或自定义规则)匹配对应食品品类
- 顺着食品文件夹的固定层级(Monthly Files SubFolder → 年份子文件夹 → 上月年月子文件夹)找到目标目录
- 将文件移动过去,共享盘内移动会自动继承目标文件夹的权限
实现代码(Google Apps Script)
直接用Google Apps Script就能搞定,不用额外工具,代码里的配置项按实际情况修改:
// 配置区 - 替换成你的实际ID和名称 const PARENT_FOLDER_ID = "你的父文件夹ID"; const CATEGORY_FOLDER_MAP = { "甜甜圈": "Donut Folder的ID", "蛋糕": "Cake Folder的ID", // 需添加更多品类可继续在此扩展 }; const MONTHLY_ROOT_FOLDER_NAME = "Monthly Files SubFolder"; function moveFoodFiles() { // 1. 计算上个月的年月信息 const now = new Date(); const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1); const targetYear = lastMonth.getFullYear(); const targetMonthName = Utilities.formatDate(lastMonth, "Asia/Shanghai", "MMMM yyyy"); // 时区可按需修改,输出格式如"August 2022" const yearFolderName = `${targetYear} SubFolder`; // 2. 获取父文件夹下的所有文件 const parentFolder = DriveApp.getFolderById(PARENT_FOLDER_ID); const files = parentFolder.getFiles(); // 3. 逐个处理文件 while (files.hasNext()) { const file = files.next(); const fileName = file.getName(); // 匹配品类:此处默认通过文件名包含品类关键词识别,可根据实际规则调整 let targetCategory = null; for (const category in CATEGORY_FOLDER_MAP) { if (fileName.includes(category)) { targetCategory = category; break; } } if (!targetCategory) { console.log(`文件${fileName}未匹配到对应品类,跳过`); continue; } // 4. 逐层定位目标文件夹 const categoryFolder = DriveApp.getFolderById(CATEGORY_FOLDER_MAP[targetCategory]); // 定位Monthly Files SubFolder let monthlyRoot = null; const monthlyFolders = categoryFolder.getFoldersByName(MONTHLY_ROOT_FOLDER_NAME); if (monthlyFolders.hasNext()) monthlyRoot = monthlyFolders.next(); else { console.log(`${targetCategory}下未找到${MONTHLY_ROOT_FOLDER_NAME},跳过文件${fileName}`); continue; } // 定位年份子文件夹 let yearFolder = null; const yearFolders = monthlyRoot.getFoldersByName(yearFolderName); if (yearFolders.hasNext()) yearFolder = yearFolders.next(); else { console.log(`${MONTHLY_ROOT_FOLDER_NAME}下未找到${yearFolderName},跳过文件${fileName}`); continue; } // 定位目标月度子文件夹 let targetFolder = null; const monthFolders = yearFolder.getFoldersByName(targetMonthName); if (monthFolders.hasNext()) targetFolder = monthFolders.next(); else { console.log(`${yearFolderName}下未找到${targetMonthName},跳过文件${fileName}`); continue; } // 5. 执行文件移动 try { file.moveTo(targetFolder); console.log(`成功移动文件${fileName}至${targetCategory}的${targetMonthName}文件夹`); } catch (err) { console.log(`移动文件${fileName}失败:${err.message}`); } } } // 创建每月定时触发:执行一次此函数,即可设置每月1号上午9点自动运行moveFoodFiles function setupMonthlyTrigger() { ScriptApp.newTrigger("moveFoodFiles") .timeBased() .onMonthDay(1) .atHour(9) .create(); }
关键注意事项
- 品类匹配规则:如果你的文件不是通过文件名识别品类(比如用文件标签、描述),可自行修改代码中
targetCategory的匹配逻辑 - 权限要求:运行脚本的账号必须拥有父文件夹、所有食品文件夹及子文件夹的编辑权限,否则无法完成文件移动
- 时区设置:代码中使用的是"Asia/Shanghai"时区,若需适配其他时区,替换为对应的时区字符串即可
- 调试建议:先手动执行
moveFoodFiles函数,通过脚本编辑器的「查看」→「日志」确认运行情况,无问题后再启用定时触发
内容的提问来源于stack exchange,提问作者scriptnewb
相关产品推荐
相关产品推荐

