Auto-Organise Google Drive with Apps Script

Learn how to auto-organise Google Drive using Apps Script. Three copy-paste scripts to sort files by type, archive old files, and rename with date prefixes.

If you have ever spent ten minutes hunting for a file that you know is somewhere in Google Drive, this guide is for you. A cluttered Drive is not a sign of disorganisation -- it is a sign that file management has been left entirely to humans who have better things to do. The problem is predictable. Files get dumped into a shared drive, folders multiply without naming conventions, and six months later nobody can agree on whether the Q3 proposal is in "Clients", "Proposals", or "Q3 Work".

Google Apps Script changes this by putting file organisation on autopilot. Apps Script is Google's built-in scripting platform, based on JavaScript, that runs directly inside your Google Workspace environment. You do not need to install anything, set up a server, or pay for a third-party automation tool. Everything runs inside Google's infrastructure, on a schedule you define, using permissions that are already tied to your Google account.

In this guide you will get three production-ready scripts and the step-by-step process for deploying them:

  • Script 1: Sort files in a staging folder by MIME type into organised subfolders
  • Script 2: Move files older than a specified number of days to an archive folder
  • Script 3: Rename files with a date prefix for consistent chronological ordering

You will also learn how to set up time-based triggers so these scripts run automatically, how to add proper error handling so problems do not go unnoticed, and what permissions you need to grant to keep things secure.

What Apps Script Can Do for Google Drive

Apps Script interacts with Google Drive through the DriveApp service, which exposes methods for listing files, creating folders, moving files, renaming them, checking their MIME types, and reading their metadata including creation date and last modified date.

The key capabilities relevant to Drive organisation are:

  • List files and folders within any folder you have access to, with optional search filters
  • Get file metadata including name, MIME type, creation date, last modified date, and file size
  • Move files between folders by adding and removing parent folders
  • Rename files by setting a new name string
  • Create folders programmatically if a destination folder does not yet exist
  • Send email notifications when a script runs, encounters errors, or moves a batch of files

Apps Script runs on Google's servers, which means it does not consume your computer's resources and continues working whether your machine is on or off. For automated Drive maintenance, this is essential -- you want organisation to happen on a reliable schedule, not only when someone remembers to run a script manually.

One important scoping note: Apps Script runs under the permissions of the Google account that created the script. It can only access files and folders that account has permission to read or edit. For shared drives, the account needs at least editor access to the relevant folders.

Before You Start: Setting Up the Script Environment

Every Apps Script project for Google Drive follows the same setup process.

  1. Open script.google.com in your browser while signed into your Google Workspace account.
  2. Click New project.
  3. Name the project something descriptive, for example "Drive Auto-Organiser".
  4. The editor opens with a default empty function. Delete it and replace it with whichever script you are setting up.
  5. Click Save (the floppy disk icon or Ctrl+S).
  6. Click Run to execute the script for the first time. Google will prompt you to review and authorise the permissions the script needs.
  7. In the authorisation dialog, click Review permissions, select your account, and click Allow.

For the scripts in this guide, you will be granting access to your Google Drive. Read through the permission list before approving -- it should only request Drive access, not Gmail, Calendar, or other services unless you have added those features yourself.

You will need the folder IDs for each folder you want the scripts to work with. To get a folder ID, navigate to the folder in Google Drive and copy the string of characters at the end of the URL. For example, in https://drive.google.com/drive/folders/1aBcDeFgHiJkLmNoPqRsTuVwXyZ, the folder ID is 1aBcDeFgHiJkLmNoPqRsTuVwXyZ.

Script 1: Sort Files by Type into Subfolders

This script reads all files in a designated staging folder and moves each file into a subfolder based on its MIME type. If the subfolder does not yet exist, the script creates it automatically.

The result is a folder structure like this:

/Staging (inbox)
/Documents
/Spreadsheets
/Presentations
/PDFs
/Images
/Videos
/Other

Every file that lands in the Staging folder gets sorted into the correct subfolder the next time the script runs.

function sortFilesByType() {
  // Replace with your actual folder IDs
  var STAGING_FOLDER_ID = 'YOUR_STAGING_FOLDER_ID';
  var SORTED_PARENT_FOLDER_ID = 'YOUR_SORTED_PARENT_FOLDER_ID';

  var stagingFolder = DriveApp.getFolderById(STAGING_FOLDER_ID);
  var sortedParent = DriveApp.getFolderById(SORTED_PARENT_FOLDER_ID);
  var files = stagingFolder.getFiles();

  // Map MIME types to human-readable folder names
  var mimeToFolder = {
    'application/vnd.google-apps.document':       'Documents',
    'application/vnd.google-apps.spreadsheet':    'Spreadsheets',
    'application/vnd.google-apps.presentation':   'Presentations',
    'application/pdf':                            'PDFs',
    'image/jpeg':                                 'Images',
    'image/png':                                  'Images',
    'image/gif':                                  'Images',
    'video/mp4':                                  'Videos',
    'video/quicktime':                            'Videos',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'Documents',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':       'Spreadsheets',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'Presentations',
  };

  var movedCount = 0;
  var errors = [];

  while (files.hasNext()) {
    var file = files.next();
    var mimeType = file.getMimeType();
    var folderName = mimeToFolder[mimeType] || 'Other';

    try {
      // Find or create the destination subfolder
      var destinationFolder;
      var existingFolders = sortedParent.getFoldersByName(folderName);

      if (existingFolders.hasNext()) {
        destinationFolder = existingFolders.next();
      } else {
        destinationFolder = sortedParent.createFolder(folderName);
      }

      // Move file: add new parent, then remove old parent
      file.moveTo(destinationFolder);
      movedCount++;

    } catch (e) {
      errors.push('Could not move ' + file.getName() + ': ' + e.message);
    }
  }

  // Log a summary
  Logger.log('Sorted ' + movedCount + ' file(s). Errors: ' + errors.length);
  if (errors.length > 0) {
    Logger.log('Error details: ' + errors.join('\n'));
  }
}

To use this script, replace YOUR_STAGING_FOLDER_ID and YOUR_SORTED_PARENT_FOLDER_ID with the actual folder IDs from your Drive. The staging folder is where files are initially uploaded; the sorted parent is where the type-based subfolders will be created.

The MIME type map covers the most common file types. To handle additional types, add entries following the same pattern. You can find the MIME type string for any file by adding a Logger.log(file.getMimeType()) line inside the loop and running the script while viewing the Logs panel (View > Logs).

Script 2: Move Old Files to an Archive Folder

Over time, active working folders accumulate files that are no longer regularly needed -- completed project documents, old report exports, superseded versions. This script identifies files that have not been modified within a specified number of days and moves them to a dedicated archive folder.

function archiveOldFiles() {
  // Replace with your actual folder IDs
  var SOURCE_FOLDER_ID = 'YOUR_SOURCE_FOLDER_ID';
  var ARCHIVE_FOLDER_ID = 'YOUR_ARCHIVE_FOLDER_ID';

  // Files not modified within this many days will be archived
  var DAYS_THRESHOLD = 90;

  var sourceFolder = DriveApp.getFolderById(SOURCE_FOLDER_ID);
  var archiveFolder = DriveApp.getFolderById(ARCHIVE_FOLDER_ID);

  var now = new Date();
  var cutoffDate = new Date(now.getTime() - (DAYS_THRESHOLD * 24 * 60 * 60 * 1000));

  var files = sourceFolder.getFiles();
  var archivedCount = 0;
  var skippedCount = 0;
  var errors = [];

  while (files.hasNext()) {
    var file = files.next();
    var lastModified = file.getLastUpdated();

    try {
      if (lastModified < cutoffDate) {
        // Create a year-based subfolder inside the archive
        var yearFolder;
        var yearLabel = Utilities.formatDate(lastModified, Session.getScriptTimeZone(), 'yyyy');
        var existingYearFolders = archiveFolder.getFoldersByName(yearLabel);

        if (existingYearFolders.hasNext()) {
          yearFolder = existingYearFolders.next();
        } else {
          yearFolder = archiveFolder.createFolder(yearLabel);
        }

        file.moveTo(yearFolder);
        archivedCount++;
      } else {
        skippedCount++;
      }

    } catch (e) {
      errors.push('Could not archive ' + file.getName() + ': ' + e.message);
    }
  }

  Logger.log(
    'Archive run complete. Archived: ' + archivedCount +
    ', Skipped (recent): ' + skippedCount +
    ', Errors: ' + errors.length
  );

  if (errors.length > 0) {
    Logger.log('Error details: ' + errors.join('\n'));
  }
}

This script archives into year-labelled subfolders within your archive location, so files from 2024 land in /Archive/2024/ and files from 2025 land in /Archive/2025/. This keeps the archive itself organised as it grows.

Adjust DAYS_THRESHOLD to match your business needs. Ninety days works well for most working folders. For project-specific folders where work cycles are shorter, thirty or sixty days may be more appropriate. For compliance or finance folders where documents need to remain accessible for regulatory periods, increase the threshold to three hundred and sixty-five days or more.

This script processes only the immediate children of the source folder, not subfolders. If you want to recurse into subfolders, add a helper function that iterates through each subfolder and calls the archive logic recursively.

Script 3: Rename Files with a Date Prefix

Consistent naming conventions are what make a folder of two hundred files navigable. The most reliable convention for most business contexts is prefixing file names with the creation date in YYYY-MM-DD format. Files then sort chronologically by default in any file view.

This script adds a date prefix to every file in a target folder that does not already have one.

function addDatePrefixToFiles() {
  // Replace with your actual folder ID
  var TARGET_FOLDER_ID = 'YOUR_TARGET_FOLDER_ID';

  var targetFolder = DriveApp.getFolderById(TARGET_FOLDER_ID);
  var files = targetFolder.getFiles();

  // Regex to detect whether a file already has a YYYY-MM-DD prefix
  var datePrefix = /^\d{4}-\d{2}-\d{2}_/;

  var renamedCount = 0;
  var skippedCount = 0;
  var errors = [];

  while (files.hasNext()) {
    var file = files.next();
    var currentName = file.getName();

    // Skip files that already have the date prefix
    if (datePrefix.test(currentName)) {
      skippedCount++;
      continue;
    }

    try {
      var createdDate = file.getDateCreated();
      var formattedDate = Utilities.formatDate(
        createdDate,
        Session.getScriptTimeZone(),
        'yyyy-MM-dd'
      );

      var newName = formattedDate + '_' + currentName;
      file.setName(newName);
      renamedCount++;

    } catch (e) {
      errors.push('Could not rename ' + currentName + ': ' + e.message);
    }
  }

  Logger.log(
    'Rename run complete. Renamed: ' + renamedCount +
    ', Already prefixed (skipped): ' + skippedCount +
    ', Errors: ' + errors.length
  );

  if (errors.length > 0) {
    Logger.log('Error details: ' + errors.join('\n'));
  }
}

The datePrefix regular expression checks whether a file name already starts with a date in YYYY-MM-DD_ format. Files that already have the prefix are skipped, which means it is safe to run this script repeatedly without creating double-prefixes.

Session.getScriptTimeZone() uses the timezone associated with your Google account. For Australian accounts this is typically Australia/Sydney or Australia/Melbourne. You can hardcode a specific timezone string if needed, for example 'Australia/Brisbane' for AEST without daylight saving.

Setting Up Time-Based Triggers

Running these scripts manually defeats the purpose of automation. Apps Script's trigger system lets you schedule any function to run on a recurring basis -- daily, weekly, or at specific hours.

To set up a trigger via the Apps Script editor:

  1. In your Apps Script project, click the clock icon in the left sidebar (Triggers).
  2. Click Add Trigger in the bottom right.
  3. Configure the trigger:
  4. Function to run: Select the function name from the dropdown (e.g., sortFilesByType)
  5. Deployment: Head deployment
  6. Event source: Time-driven
  7. Time-based trigger type: Day timer (for daily runs) or Week timer (for weekly runs)
  8. Time of day: Choose a time when Drive activity is low, such as 2am to 3am
  9. Click Save.

Recommended trigger schedules for each script:

  • sortFilesByType -- Run daily at 2am. Files uploaded during the day are sorted overnight so the folder is clean by morning.
  • archiveOldFiles -- Run weekly on Sunday at 3am. Archiving is a lower-frequency task and weekly is sufficient for most use cases.
  • addDatePrefixToFiles -- Run daily at 2:30am, or trigger it manually when you set up a new project folder. Daily runs ensure any newly uploaded files get prefixed before anyone starts looking for them.

Each trigger fires independently. If one script fails, the others are unaffected.

To set up a trigger programmatically (useful when deploying scripts across multiple accounts):

function createTriggers() {
  // Daily trigger at 2am for file sorting
  ScriptApp.newTrigger('sortFilesByType')
    .timeBased()
    .everyDays(1)
    .atHour(2)
    .create();

  // Weekly trigger on Sunday at 3am for archiving
  ScriptApp.newTrigger('archiveOldFiles')
    .timeBased()
    .onWeekDay(ScriptApp.WeekDay.SUNDAY)
    .atHour(3)
    .create();
}

Run createTriggers() once and the scheduled triggers will be set. You can review and delete triggers at any time from the Triggers panel in the Apps Script editor.

Error Handling and Email Notifications

The scripts above log errors to the Apps Script log viewer (View > Logs), which is useful during development. For production deployments, you want errors surfaced proactively rather than requiring someone to check the logs.

Add email notification to any script by inserting a MailApp.sendEmail() call in the error handling block:

function sortFilesByTypeWithNotification() {
  var STAGING_FOLDER_ID = 'YOUR_STAGING_FOLDER_ID';
  var SORTED_PARENT_FOLDER_ID = 'YOUR_SORTED_PARENT_FOLDER_ID';
  var NOTIFICATION_EMAIL = 'your.email@yourdomain.com.au';

  var stagingFolder = DriveApp.getFolderById(STAGING_FOLDER_ID);
  var sortedParent = DriveApp.getFolderById(SORTED_PARENT_FOLDER_ID);
  var files = stagingFolder.getFiles();

  var mimeToFolder = {
    'application/vnd.google-apps.document':     'Documents',
    'application/vnd.google-apps.spreadsheet':  'Spreadsheets',
    'application/vnd.google-apps.presentation': 'Presentations',
    'application/pdf':                          'PDFs',
    'image/jpeg':                               'Images',
    'image/png':                                'Images',
    'video/mp4':                                'Videos',
  };

  var movedCount = 0;
  var errors = [];

  while (files.hasNext()) {
    var file = files.next();
    var mimeType = file.getMimeType();
    var folderName = mimeToFolder[mimeType] || 'Other';

    try {
      var destinationFolder;
      var existingFolders = sortedParent.getFoldersByName(folderName);

      if (existingFolders.hasNext()) {
        destinationFolder = existingFolders.next();
      } else {
        destinationFolder = sortedParent.createFolder(folderName);
      }

      file.moveTo(destinationFolder);
      movedCount++;

    } catch (e) {
      errors.push(file.getName() + ': ' + e.message);
    }
  }

  // Send a summary email if there were errors or files were moved
  if (errors.length > 0 || movedCount > 0) {
    var subject = 'Drive Organiser: ' + movedCount + ' file(s) sorted';
    var body = 'Run completed.\n\nFiles sorted: ' + movedCount +
               '\nErrors: ' + errors.length;

    if (errors.length > 0) {
      body += '\n\nError details:\n' + errors.join('\n');
      subject = '[ACTION REQUIRED] Drive Organiser errors detected';
    }

    MailApp.sendEmail(NOTIFICATION_EMAIL, subject, body);
  }
}

Using MailApp.sendEmail() requires Gmail send permission, which is a separate authorisation from the Drive permission. When you run this version for the first time, the authorisation dialog will include Gmail access in addition to Drive access.

Keep the error reporting targeted. Send emails only when something actually happened -- files were moved, or errors occurred. An email every night saying "0 files processed, 0 errors" creates notification fatigue and will get ignored or filtered out.

Apps Script also provides built-in failure notifications for triggers. In the Triggers panel, you can set any trigger to automatically email the script owner if the trigger fails due to an unhandled exception. Enable this under the trigger settings by setting the "Failure notification settings" option to "Notify me immediately".

Permissions and Security

When you run an Apps Script for the first time, Google displays a permissions dialog that lists exactly what access the script is requesting. For the scripts in this guide, the relevant permissions are:

  • See and download all your Google Drive files -- Required to read file metadata, list folder contents, and check MIME types
  • See, edit, create, and delete all your Google Drive files -- Required to move files between folders and rename them
  • Send email as you -- Required only if you have added email notification using MailApp

These are broad permissions, but they are scoped to the account that authorises the script. The script cannot access files outside that account's Drive unless the account already has sharing access to those files.

Security considerations for team environments:

  • Do not share your script project with edit access to people who do not need to modify it. Viewers can see the script code; editors can change what it does. Use the Share settings in the Apps Script project to control access.
  • Review the folder IDs in the script before authorising. A script targeting the wrong folder ID -- for example, a root-level shared drive -- could move or rename far more files than intended.
  • Test with a small sample folder first. Before pointing a script at a live working folder with hundreds of files, create a test folder with five to ten sample files and confirm the script behaves as expected.
  • Keep scripts in a dedicated shared drive or Shared Drive if multiple administrators need to manage them. Personal Drive scripts are only accessible to the owner.
  • Avoid storing credentials or API keys in script code. The scripts in this guide do not require external credentials, but if you extend them to interact with external services, use the Properties Service (PropertiesService.getScriptProperties()) to store sensitive values rather than hardcoding them.

For Google Workspace organisations, administrators can restrict whether end users can authorise third-party and internal Apps Scripts by configuring OAuth app policies in the Admin Console. Internal scripts created within the same Google Workspace domain are typically trusted by default, but check your organisation's settings if you encounter authorisation errors.

Practical Examples for Australian Businesses

Professional services firms can use the staging folder approach as a standard file intake process. When a client sends documents via email, staff save attachments to the staging folder. The nightly sort script files PDFs into /PDFs/, spreadsheets into /Spreadsheets/, and Word documents into /Documents/. The date prefix script then ensures every file has a clear timestamp. After ninety days, the archive script moves completed matter documents out of the active working area.

Real estate agencies dealing with high volumes of listing photos can use the image sorting capability to automatically separate JPEGs and PNGs into an Images folder, keeping property documents like contracts and disclosure statements in their own location without manual intervention.

Accounts and finance teams benefit significantly from the archive script. Financial year-end is much cleaner when the previous year's working files have already been moved to /Archive/2025/ automatically, leaving the current working folder containing only current-year documents.

Marketing teams producing regular content -- social media assets, draft documents, presentation files -- can use the date prefix script to ensure that when twelve versions of a campaign brief exist, the naming makes the chronological order immediately apparent without anyone needing to check file properties.

Building on these scripts, Google Workspace provides the full infrastructure for sophisticated Drive automation without additional subscriptions.

Google Workspace is the platform that makes Apps Script available as a built-in feature. Business Starter, Business Standard, and Business Plus plans all include full Apps Script access with no additional cost. For Australian businesses that have not yet moved to Google Workspace, or that are considering upgrading their plan, the referral link above covers current pricing and plan comparisons. If your team is managing significant volumes of files across shared drives, Business Standard's 2TB pooled storage per user and shared drive support make a meaningful practical difference to how well these scripts perform at scale.

The Apps Script documentation covers the complete DriveApp reference, including every available method for interacting with files and folders. The reference is thorough and includes working examples for the most common operations.

Conclusion

Google Drive does not organise itself, but Apps Script can. The three scripts in this guide cover the most impactful automated maintenance tasks: sorting files by type so uploads land in the right place, archiving old files so active folders stay relevant, and prefixing file names with dates so chronological order is always obvious.

None of these scripts require more than ten minutes to set up once you have your folder IDs ready. The triggers require another five minutes to configure. After that, the maintenance runs silently on whatever schedule you define -- nightly, weekly, or both -- without anyone needing to remember to do it.

Start with whichever script addresses your most immediate pain point. If your Drive has a general clutter problem, begin with the type sorter. If an active folder has become a graveyard of old files, deploy the archive script first. If file naming is your biggest frustration, the date prefix script delivers results immediately.

The broader point is that every hour your team spends manually organising Drive is an hour not spent on work that actually requires human judgement. Apps Script converts that repetitive maintenance into a scheduled background process, and over a year the cumulative time recovered is substantial.


Ash Ganda is the founder of CloudGeeks, a Google Workspace consultancy helping Australian SMBs get more from their cloud tools. He writes about practical technology strategies at insights.cloudgeeks.com.au.