修改Google Apps脚本:迁移最后编辑超2小时的共享云端硬盘文件
修改后的代码(仅移动最后编辑超2小时的文件)
function moveFiles(sourceDriveId, targetFolderId) { // 计算当前时间往前推2小时的时间戳(单位:毫秒) const twoHoursAgo = new Date().getTime() - 2 * 60 * 60 * 1000; const targetFolder = DriveApp.getFolderById(targetFolderId); const sourceDrive = DriveApp.getFolderById(sourceDriveId); const files = sourceDrive.getFiles(); while(files.hasNext()){ const file = files.next(); // 判断文件最后编辑时间是否早于2小时前 if(file.getLastUpdated().getTime() < twoHoursAgo) { file.makeCopy(file.getName(), targetFolder); Drive.Files.remove(file.getId(), {supportsAllDrives: true}); } } } function test() { moveFiles("0AHJ7TY_Fdd1hUk9PVx", "0AEzW-YOJoXAEUk9PVx"); }
修改说明
- 移除原代码中
lastUpdate相关逻辑:文件移动后会从源文件夹删除,不会重复处理,无需记录上次运行时间 - 新增
twoHoursAgo变量:通过当前时间减去2小时的毫秒数,得到判断阈值 - 替换判断条件:使用
file.getLastUpdated()获取文件最后编辑时间,仅当该时间早于2小时前时,执行移动操作
保留原逻辑的版本(同时满足「上次运行后新增」+「最后编辑超2小时」)
如果需要保留原代码中「仅处理上次脚本运行后新增文件」的规则,同时叠加「最后编辑超2小时」的条件,可使用以下代码:
function moveFiles(sourceDriveId, targetFolderId) { const scriptProperties = PropertiesService.getScriptProperties(); let lastUpdate = scriptProperties.getProperty('lastUpdate'); // 首次运行初始化上次运行时间 if(lastUpdate == null) { lastUpdate = new Date().getTime(); scriptProperties.setProperty('lastUpdate', lastUpdate); return; } lastUpdate = parseInt(lastUpdate); // 转换为数字类型用于时间比较 // 计算2小时前的时间戳 const twoHoursAgo = new Date().getTime() - 2 * 60 * 60 * 1000; const targetFolder = DriveApp.getFolderById(targetFolderId); const sourceDrive = DriveApp.getFolderById(sourceDriveId); const files = sourceDrive.getFiles(); while(files.hasNext()){ const file = files.next(); // 同时满足两个条件才执行移动 if(file.getDateCreated().getTime() > lastUpdate && file.getLastUpdated().getTime() < twoHoursAgo) { file.makeCopy(file.getName(), targetFolder); Drive.Files.remove(file.getId(), {supportsAllDrives: true}); } } scriptProperties.setProperty('lastUpdate', new Date().getTime()); } function test() { moveFiles("0AHJ7TY_Fdd1hUk9PVx", "0AEzW-YOJoXAEUk9PVx"); }
内容的提问来源于stack exchange,提问作者Exeter Trees
相关产品推荐
相关产品推荐

