Unlock Automated Google Drive Folder Monitoring with Apps Script
Stay instantly informed about new or modified CSV and Google Sheets files in any Drive folder using a custom, automated script.
Monitoring specific Google Drive folders for changes, especially for critical file types like CSVs and Google Sheets, can be essential for streamlined workflows and data management. This guide provides a comprehensive Google Apps Script solution that automates this process, sending you email notifications whenever relevant files are added or updated. The script is designed to be standalone, reside on a Shared Drive, and run hourly or on demand.
Highlights: Key Benefits of This Script
- Automated Vigilance: Set up an hourly check for your specified Google Drive folder, ensuring you're always up-to-date without manual effort.
- Targeted Monitoring: Focus exclusively on CSV and Google Sheets files, filtering out noise from other file types.
- Instant Notifications: Receive detailed email alerts summarizing new additions and modifications, complete with direct links to the files.
- Standalone & Shared Drive Ready: Deploy this script directly within your Google Workspace, including Shared Drives, without external dependencies.
Understanding the Automation: How the Script Works
This Google Apps Script leverages the power of Google's own services to provide a seamless monitoring solution. Here’s a breakdown of its core functionality:
Automating Google Drive tasks enhances productivity and data integrity.
Core Components
- Folder Identification: You specify the exact Google Drive folder to monitor using its unique ID.
- File Type Filtering: The script specifically looks for files with MIME types corresponding to CSV (
MimeType.CSV) and Google Sheets (MimeType.GOOGLE_SHEETS). - State Tracking with Properties Service: To detect changes, the script stores metadata (file ID, name, URL, and last modified timestamp) of the relevant files from its previous run. This information is stored securely using Google Apps Script's
PropertiesService, which is scoped to the script itself, making it truly standalone. - Change Detection Logic:
- New Files: Any CSV or Google Sheets file found in the folder that wasn't present in the stored metadata is identified as new.
- Modified Files: For existing files, the script compares the current
lastUpdatedtimestamp with the stored timestamp. A more recent timestamp indicates a modification.
- Email Notifications: If new files are added or existing ones are modified, an HTML-formatted email is sent to your specified address. This email includes lists of the new and/or changed files, with direct links for quick access.
- Automated Execution (Triggers): A time-driven trigger is set up to run the script automatically every hour.
- Manual Execution: You can also run the script manually at any time directly from the Apps Script editor.
Workflow Mindmap
The following mindmap illustrates the operational flow of the Google Drive monitoring script, from initialization to state update and notification.
The Google Apps Script Code
Below is the complete standalone script. Copy and paste this code into a new Google Apps Script project.
// --- CONFIGURATION --- // Replace with the ID of the Google Drive folder you want to monitor. // Example: If folder URL is https://drive.google.com/drive/folders/ABC123XYZ, then ID is "ABC123XYZ" const MONITORED_FOLDER_ID = "YOUR_FOLDER_ID_HERE"; // Replace with the email address where notifications should be sent. const NOTIFICATION_EMAIL = "YOUR_EMAIL_ADDRESS_HERE"; // Key used to store file metadata in script properties. You generally don't need to change this. const SCRIPT_PROPERTY_KEY_METADATA = "driveFolderMonitorMetadata_v1"; // --- END CONFIGURATION --- /** * Main function to check the monitored Google Drive folder for new or updated * CSV and Google Sheets files, and send email notifications if changes are detected. * This function is intended to be run by a trigger or manually. */ function checkDriveFolderAndNotify() { try { const folder = DriveApp.getFolderById(MONITORED_FOLDER_ID); if (!folder) { Logger.log("Error: Monitored folder with ID '" + MONITORED_FOLDER_ID + "' not found or access denied."); // Consider sending an admin error email here if persistent issues occur. return; } const folderName = folder.getName(); Logger.log("Starting check for folder: '" + folderName + "' (ID: " + MONITORED_FOLDER_ID + ")"); const scriptProperties = PropertiesService.getScriptProperties(); const previousMetadataJson = scriptProperties.getProperty(SCRIPT_PROPERTY_KEY_METADATA); let previousMetadata = {}; if (previousMetadataJson) { try { previousMetadata = JSON.parse(previousMetadataJson); } catch (e) { Logger.log("Error parsing previous metadata JSON: " + e.toString() + ". Starting with empty metadata."); previousMetadata = {}; } } const currentMetadata = {}; const newFiles = []; const modifiedFiles = []; const filesIterator = folder.getFiles(); while (filesIterator.hasNext()) { const file = filesIterator.next(); const mimeType = file.getMimeType(); // Process only CSV or Google Sheets files if (mimeType === MimeType.CSV || mimeType === MimeType.GOOGLE_SHEETS) { const fileId = file.getId(); const fileName = file.getName(); const fileUrl = file.getUrl(); const lastUpdated = file.getLastUpdated().getTime(); // Timestamp in milliseconds currentMetadata[fileId] = { name: fileName, url: fileUrl, lastUpdated: lastUpdated, type: mimeType === MimeType.CSV ? "CSV" : "Google Sheet" }; if (!previousMetadata[fileId]) { newFiles.push(currentMetadata[fileId]); Logger.log("New file detected: " + fileName); } else if (lastUpdated > previousMetadata[fileId].lastUpdated) { // Check for a significant time difference to avoid notifications for micro-changes (e.g., > 10 seconds) // This is optional and depends on how Drive updates timestamps for minor view-only changes. // For simplicity, any timestamp change is considered a modification here. modifiedFiles.push(currentMetadata[fileId]); Logger.log("Modified file detected: " + fileName); } } } if (newFiles.length > 0 || modifiedFiles.length > 0) { sendNotificationEmail(newFiles, modifiedFiles, folderName); } else { Logger.log("No new or modified CSV/Google Sheets files detected in '" + folderName + "'."); } // Save current metadata for the next run scriptProperties.setProperty(SCRIPT_PROPERTY_KEY_METADATA, JSON.stringify(currentMetadata)); Logger.log("Successfully updated metadata for folder: '" + folderName + "'."); } catch (e) { Logger.log("FATAL ERROR in checkDriveFolderAndNotify: " + e.toString() + "\nStack: " + e.stack); // Optionally send an error notification email to the admin/NOTIFICATION_EMAIL MailApp.sendEmail( NOTIFICATION_EMAIL, "Script Error: Google Drive Folder Monitor", "An error occurred while monitoring folder ID " + MONITORED_FOLDER_ID + ":\n\n" + e.toString() + "\n\nStack Trace:\n" + e.stack ); } } /** * Sends an email notification summarizing new and modified files. * @param {Array} newFiles - Array of objects representing new files. * @param {Array} modifiedFiles - Array of objects representing modified files. * @param {string} folderName - The name of the monitored folder. */ function sendNotificationEmail(newFiles, modifiedFiles, folderName) { let emailSubject = "Google Drive Alert: Changes in Folder '" + folderName + "'"; let emailBody = "<p>Hello,</p>"; emailBody += "<p>The Google Drive monitoring script detected the following changes in the folder <strong>'" + folderName + "'</strong> (ID: " + MONITORED_FOLDER_ID + "):</p>"; if (newFiles.length > 0) { emailBody += "<h3>New Files Added:</h3><ul>"; newFiles.forEach(file => { emailBody += <code><li><a href="${file.url}" target="_blank">${file.name}</a> (${file.type}) - Added around: ${new Date(file.lastUpdated).toLocaleString()}</li>; }); emailBody += "</ul>"; } if (modifiedFiles.length > 0) { emailBody += "<h3>Files Modified:</h3><ul>"; modifiedFiles.forEach(file => { emailBody +=<li><a href="${file.url}" target="_blank">${file.name}</a> (${file.type}) - Modified at: ${new Date(file.lastUpdated).toLocaleString()}</li>; }); emailBody += "</ul>"; } emailBody += "<p>--<br/>This is an automated notification from your Google Apps Script.</p>"; MailApp.sendEmail({ to: NOTIFICATION_EMAIL, subject: emailSubject, htmlBody: emailBody }); Logger.log("Notification email sent to " + NOTIFICATION_EMAIL + " for changes in folder '" + folderName + "'."); } /** * Creates a time-driven trigger to run the 'checkDriveFolderAndNotify' function every hour. * Run this function once manually from the Apps Script editor to set up the trigger. * It will remove any existing triggers for the same function to prevent duplicates. */ function createHourlyTriggerForMonitoring() { // Delete existing triggers for this function to prevent duplicates const allTriggers = ScriptApp.getProjectTriggers(); for (let i = 0; i < allTriggers.length; i++) { if (allTriggers[i].getHandlerFunction() === "checkDriveFolderAndNotify") { ScriptApp.deleteTrigger(allTriggers[i]); Logger.log("Deleted existing trigger: " + allTriggers[i].getUniqueId()); } } // Create a new hourly trigger ScriptApp.newTrigger("checkDriveFolderAndNotify") .timeBased() .everyHours(1) .create(); Logger.log("Hourly trigger created successfully for 'checkDriveFolderAndNotify'."); SpreadsheetApp.getUi().alert("Hourly trigger created successfully for 'checkDriveFolderAndNotify'."); // Or use Logger.log if running headlessly. } /** * Allows manual execution of the monitoring script. * Select this function in the Apps Script editor and click "Run". */ function manualRunMonitoring() { Logger.log("Manual run of folder monitoring initiated by user."); checkDriveFolderAndNotify(); Logger.log("Manual run completed."); SpreadsheetApp.getUi().alert("Manual run of folder monitoring completed. Check logs for details."); // Or use Logger.log. } /** * OPTIONAL: Deletes all triggers associated with this script project. * Useful for cleanup if you no longer need the automated monitoring. */ function deleteAllProjectTriggers() { const triggers = ScriptApp.getProjectTriggers(); let count = 0; for (let i = 0; i < triggers.length; i++) { // You could be more specific here if you only want to delete triggers for 'checkDriveFolderAndNotify' ScriptApp.deleteTrigger(triggers[i]); count++; } Logger.log(count + " trigger(s) deleted from the project."); if (count > 0) { SpreadsheetApp.getUi().alert(count + " trigger(s) deleted."); } else { SpreadsheetApp.getUi().alert("No triggers found to delete."); } } /** * OPTIONAL: Resets the stored file metadata. * Useful for testing the script as if it's running for the first time. */ function resetMonitoredData() { PropertiesService.getScriptProperties().deleteProperty(SCRIPT_PROPERTY_KEY_METADATA); Logger.log("Stored folder metadata (property key: '" + SCRIPT_PROPERTY_KEY_METADATA + "') has been reset."); SpreadsheetApp.getUi().alert("Stored folder metadata has been reset."); }
Setup and Usage Instructions
Leverage Google Workspace tools for powerful automation.
- Create a New Apps Script Project:
- Go to script.google.com.
- Click on "New project".
- Give your project a name (e.g., "Drive Folder Monitor").
- Paste the Script Code:
- Delete any default code in the `Code.gs` file.
- Copy the entire script provided above and paste it into the `Code.gs` file.
- Configure the Script:
- In the script, find the `CONFIGURATION` section at the top.
- Replace
"YOUR_FOLDER_ID_HERE"with the actual ID of the Google Drive folder you wish to monitor. You can find the folder ID in its URL (e.g., if the URL ishttps://drive.google.com/drive/folders/ABC123XYZ123, the ID isABC123XYZ123). - Replace
"YOUR_EMAIL_ADDRESS_HERE"with the email address where you want to receive notifications.
- Save the Script: Click the floppy disk icon (Save project) in the Apps Script editor.
- Authorize the Script:
- Before the script can run (either manually or via a trigger), it needs your authorization to access your Google Drive and send emails on your behalf.
- Select the function
manualRunMonitoringfrom the function dropdown list (next to the "Debug" button). - Click the "Run" button.
- A "Authorization required" dialog will appear. Click "Review permissions."
- Choose the Google account you want to authorize the script with.
- You might see a "Google hasn’t verified this app" screen. If so, click "Advanced" and then "Go to [Your Script Name] (unsafe)". This is standard for custom scripts you've written.
- Review the permissions the script needs (e.g., manage files in Google Drive, send email as you) and click "Allow."
- Set Up the Hourly Trigger:
- In the Apps Script editor, select the function
createHourlyTriggerForMonitoringfrom the function dropdown list. - Click the "Run" button. This will set up the script to run automatically every hour. You only need to do this once.
- You can verify the trigger by going to the "Triggers" page (clock icon on the left sidebar). You should see a trigger for `checkDriveFolderAndNotify` set to run hourly.
- In the Apps Script editor, select the function
- Standalone Script on Shared Drive:
- This script is standalone. The `.gs` file itself is stored in your Google Drive.
- You can move this script file into a Shared Drive if desired. The script will continue to function as long as the account that authorized it (and under which the triggers run) has access to the `MONITORED_FOLDER_ID`.
- Manual Execution (Optional):
- To run the check immediately, select `manualRunMonitoring` from the dropdown and click "Run."
Monitoring Script Aspects: A Comparative View
This radar chart provides a conceptual comparison of this Google Apps Script solution against native Drive notifications and manual checking, based on several key aspects. "This Script" refers to the solution provided on this page.
Note: "Notification Timeliness" for the script is hourly, while native notifications can be near real-time. "Resource Efficiency" refers to how it uses Google Apps Script quotas, which are generally generous for this type of task.
Key Configuration Parameters
The script's behavior is primarily controlled by constants defined at the beginning of the code. Here's a summary:
| Parameter | Description | How to Set | Example Value |
|---|---|---|---|
MONITORED_FOLDER_ID |
The unique identifier of the Google Drive folder that the script will monitor. | Edit directly in the script code. Obtain from the folder's URL. | "1a2b3c4d5e6f7g8h9i0j..." |
NOTIFICATION_EMAIL |
The email address to which all change notifications will be sent. | Edit directly in the script code. | "your.email@example.com" |
SCRIPT_PROPERTY_KEY_METADATA |
The internal key used by the script to store information about files between runs. Usually, you don't need to change this. | Pre-defined in the script. Modifying it will cause the script to lose its history of monitored files (effectively a reset). | "driveFolderMonitorMetadata_v1" |
| Trigger Frequency | How often the script runs automatically. | Set within the createHourlyTriggerForMonitoring function (e.g., .everyHours(1)). Can be adjusted (e.g., .everyDays(1), .everyMinutes(30) - be mindful of quotas for very frequent triggers). |
Every 1 hour (default) |
Visualizing File Monitoring with Apps Script
This YouTube video provides insights into monitoring file updates on Google Drive using Google Apps Script, which aligns with the principles of the script discussed here.
Learn more about monitoring Google Drive files with Apps Script. (Video: Monitor File Updates on Google Drive with Google Apps Script)
Important Considerations
- Permissions: The script requires your authorization to access Google Drive and send emails. This is a one-time setup step. The triggers will run under the authority of the user who created them.
- Shared Drive Access: If the monitored folder is in a Shared Drive, ensure the account authorizing the script has at least "Viewer" access to that folder and its contents. For the script to "live" on a Shared Drive, simply move the Apps Script file (`.gs`) to the Shared Drive.
- File Deletions: This script focuses on new and modified files. It does not currently notify about file deletions from the monitored folder. Extending this functionality is possible but adds complexity.
- Subfolders: The provided script monitors files directly within the specified folder only. It does not recursively monitor subfolders. Modification would be needed for subfolder monitoring.
- Google Apps Script Quotas: Google sets daily quotas for services like MailApp (email sending) and script runtime. For hourly monitoring of a reasonably sized folder, this script should stay well within typical quotas. Very frequent triggers (e.g., every minute) or extremely large folders might require optimization or quota considerations.
- Error Handling: The script includes basic error logging to the Apps Script console (View > Logs). For critical applications, you might consider enhancing error notifications (e.g., sending an email to an admin if the script encounters a fatal error). The current script does send an email for fatal errors.
- Timezone: Timestamps in notifications (`.toLocaleString()`) will be based on the timezone settings of the Google account under which the script is running.
Frequently Asked Questions (FAQ)
What if I want to monitor file types other than CSV and Google Sheets?
How can I change the notification frequency?
What happens if I rename the monitored folder?
Can I monitor multiple folders?
How do I stop the script from running automatically?
Will I get notified if a file is just viewed but not changed?
Conclusion
This Google Apps Script provides a powerful, customizable, and automated solution for monitoring specific folders in your Google Drive for new or changed CSV and Google Sheets files. By leveraging `PropertiesService` for state management and time-driven triggers for automation, you can stay informed about critical file updates without manual intervention, directly within your Google Workspace environment. Remember to configure the script with your specific folder ID and notification email, and authorize it to ensure smooth operation.
Recommended Next Steps & Further Exploration
- Explore how to modify this Google Apps Script to recursively monitor subfolders within the main Google Drive folder.
- Investigate methods for extending the script to detect and notify about files deleted from the monitored Google Drive folder.
- Learn about advanced error handling techniques in Google Apps Script for creating more robust Drive monitoring solutions, including custom error reports.
- Discover how to integrate Google Apps Script with Google Chat webhooks to send Drive folder notifications to a Chat space instead of email.
Referenced Search Results
This response was synthesized using information and concepts found in the following resources: