如何在特定文件夹新增文件时触发Google Script运行?
实现Google Drive指定文件夹新增文件时自动触发Google Script
Great news—this is totally achievable, and you can ditch that 1-minute interval trigger for a much more responsive setup! Here's how to make your script run almost instantly when a file is added to your target folder:
Option 1: Use Drive's onChange Trigger (Basic & Reliable)
This is the simplest approach, and it’ll trigger your script whenever any change happens in your Drive—we’ll just add a check to only act on new files in your specific folder.
- Open your Google Script project
- Go to the Triggers tab (left sidebar) and click Add trigger
- Configure the trigger like this:
- Choose the function you want to run (e.g.,
processNewFile) - Select From drive as the event source
- Pick On change as the event type
- Choose the function you want to run (e.g.,
- Save the trigger—you’ll need to authorize the script if it’s your first time setting this up
Next, update your function to filter for only new files in your target folder. Here’s a sample implementation:
function processNewFile(e) { // Replace this with your target folder's ID (grab it from the folder's URL) const TARGET_FOLDER_ID = "your-unique-folder-id"; // Only react when a file is added/inserted if (!["add", "insert"].includes(e.changeType)) return; try { const item = DriveApp.getFileById(e.id); // Check if the file's parent is your target folder const parentFolders = item.getParents(); while (parentFolders.hasNext()) { const parent = parentFolders.next(); if (parent.getId() === TARGET_FOLDER_ID) { // Put your file-processing logic here! console.log(`New file detected: ${item.getName()}`); // Example: Move it, rename it, run OCR, etc. break; } } } catch (err) { // Ignore if the item is a folder (we only care about files) console.log(`Ignored folder change: ${err.message}`); } }
Option 2: Advanced Drive API for Granular Control
If you need even more precision (e.g., only trigger for files directly added to the folder, not subfolders), enable the Drive API advanced service:
- In the script editor, go to Services > Add service
- Find and add the Drive API service
- You can then use
Drive.Files.list()with filters to check the file's parent hierarchy more efficiently, but for most use cases, Option 1 is more than enough.
Key Notes
- The
onChangetrigger typically fires within a few seconds of the file being added—way faster than a 1-minute interval - Make sure your script stays within Google’s execution limits (max 6 minutes per run, quota limits for Drive operations)
- Test with a few test files to confirm the trigger works as expected
内容的提问来源于stack exchange,提问作者Lontronix
相关产品推荐
相关产品推荐

