Google Drive AutomationDifficulty: Intermediate⚡ Nightly Trigger

Auto-Organize Google Drive Uploads into Year / Month Subfolders

Scans an incoming upload folder in Google Drive, examines file creation dates, and moves files into organized subfolders formatted as YYYY/MM.

Required OAuth Scopes: https://www.googleapis.com/auth/drive
Code.gs (Apps Script V8 Runtime)
function autoOrganizeDriveUploads() {
  const rootFolderId = 'PASTE_INBOX_FOLDER_ID_HERE';
  const inbox = DriveApp.getFolderById(rootFolderId);
  const files = inbox.getFiles();
  
  while (files.hasNext()) {
    const file = files.next();
    const date = file.getDateCreated();
    const yearStr = String(date.getFullYear());
    const monthStr = ('0' + (date.getMonth() + 1)).slice(-2);
    
    // Resolve or create Year folder
    let yearFolder = inbox.getFoldersByName(yearStr);
    let targetYear = yearFolder.hasNext() ? yearFolder.next() : inbox.createFolder(yearStr);
    
    // Resolve or create Month folder
    let monthFolder = targetYear.getFoldersByName(monthStr);
    let targetMonth = monthFolder.hasNext() ? monthFolder.next() : targetYear.createFolder(monthStr);
    
    file.moveTo(targetMonth);
  }
}

Line-by-Line Code Explanation

Line 3-4: Iterates through files sitting in the root inbox folder.
Line 8-10: Extracts creation year and zero-padded month string.
Line 13-18: Checks if subfolders exist, creates them if absent, and moves file.

Step-by-Step Setup & Deployment

  1. Create an "Inbox" folder in Google Drive and paste its ID in Line 2.
  2. Set up a nightly time-driven trigger.

Best Practices for Quota & Rate Limit Management

When deploying this automation in Google Workspace, adhere to these operational principles:

  • Batch Reads & Writes: Never execute getValue() or setValue() inside loops. Read ranges into memory in 1 call, process arrays in V8 memory, and commit changes with a single setValues() call.
  • Execution Timeouts: Apps Script terminates scripts exceeding 6 minutes. For multi-thousand row datasets, implement batch pagination with resume timestamps stored in PropertiesService.
  • OAuth Permissions: Scope your manifest (appsscript.json) narrowly to prevent security prompts from alarming external team members.

Frequently Asked Questions

Is Google Apps Script completely free to use?

Yes. Google Apps Script is built into all free Google accounts and Google Workspace editions. There are no server fees or subscription costs for running scripts within daily quotas.

Can I run this script on an automated schedule without keeping my computer on?

Yes. Time-driven triggers execute on Google's cloud infrastructure. Your script will run reliably even when your computer is closed or offline.

More Google Drive Automation Snippets