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

请求编写Google Drive子文件夹旧监控录像删除脚本

Google Drive 自动删除指定文件夹下超30天录像文件脚本

以下脚本可实现删除指定父文件夹(如Backups)下所有摄像头子文件夹中超过30天的录像文件,同时保留子文件夹本身:

function deleteOldFiles() {
  // 替换为你的父文件夹名称
  const parentFolderName = "Backups";
  // 设定保留天数
  const daysToKeep = 30;
  const cutoffDate = new Date();
  cutoffDate.setDate(cutoffDate.getDate() - daysToKeep);

  // 获取父文件夹
  const parentFolders = DriveApp.getFoldersByName(parentFolderName);
  if (!parentFolders.hasNext()) {
    console.log(`未找到名为${parentFolderName}的父文件夹`);
    return;
  }
  const parentFolder = parentFolders.next();

  // 遍历所有摄像头子文件夹
  const cameraFolders = parentFolder.getFolders();
  while (cameraFolders.hasNext()) {
    const cameraFolder = cameraFolders.next();
    console.log(`正在处理摄像头文件夹: ${cameraFolder.getName()}`);

    // 遍历子文件夹内的所有文件
    const files = cameraFolder.getFiles();
    let deletedCount = 0;
    while (files.hasNext()) {
      const file = files.next();
      const fileCreatedDate = file.getDateCreated();

      // 判断文件是否超过保留天数
      if (fileCreatedDate < cutoffDate) {
        file.setTrashed(true); // 移至回收站,如需永久删除可改用file.remove()
        deletedCount++;
        console.log(`已删除文件: ${file.getName()},创建时间: ${fileCreatedDate}`);
      }
    }
    console.log(`文件夹${cameraFolder.getName()}处理完成,共删除${deletedCount}个旧文件\n`);
  }
}

使用说明

  • 修改配置:将脚本中的parentFolderName替换为你的实际父文件夹名称(如Backups),可调整daysToKeep设置保留天数
  • 部署步骤:
    1. 打开Google Apps Script,新建空白项目
    2. 将上述代码粘贴到编辑器中,保存项目(命名如DriveOldFileCleaner)
    3. 点击运行按钮,首次运行需授权脚本访问Google Drive权限
    4. 设置定期触发器:点击左侧「触发器」图标,添加触发器,选择deleteOldFiles函数,设置触发时间(如每天/每周运行一次)

注意事项

  • 脚本默认将旧文件移至回收站,如需永久删除,可将file.setTrashed(true)替换为file.remove()
  • 请先在测试文件夹中验证脚本逻辑,避免误删重要文件
  • 回收站文件仍会占用存储空间,需定期清空

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 23:40:40