How to Automate Google Drive: Organizing Files and Folders with Apps Script

How to Automate Google Drive: Organizing Files and Folders with Apps Script

Google Drive is a versatile platform for storing and managing files and folders. With Google Apps Script, you can automate and streamline your file organization tasks, making your work more efficient. In this blog post, we'll explore how you can automate Google Drive to organize files and folders with Apps Script.

Why Use Google Apps Script for Google Drive?

Google Apps Script is a powerful scripting language for automating tasks and extending the functionality of Google Workspace applications, including Google Drive. Here are some compelling reasons to use it for file organization:

  • Automate Repetitive Tasks: Automatically sort and categorize files based on rules and criteria.
  • Enhanced Collaboration: Streamline file-sharing processes for teams and projects.
  • Data Backup: Create automated backups of critical files and folders.
  • Customization: Tailor your file organization scripts to fit your unique needs.

Getting Started with Google Apps Script for Google Drive

Follow these simple steps to get started with automating Google Drive using Apps Script:

  1. Open Google Drive and create a new folder or open an existing one.
  2. Click on the "Extensions" menu and select "Apps Script."
  3. Replace the default code with your custom script and save it.
  4. Configure triggers to run the script automatically based on specific events or schedules.

Example 1 : Auto-Organizing Files by Type

Let's say you want to automatically organize files in your Google Drive folder based on their types, such as documents, images, and spreadsheets. With Google Apps Script, you can create a script like this:

  function organizeFilesByType() {
  var parentFolderId = 'YOUR_PARENT_FOLDER_ID'; // Replace with your folder ID
  var parentFolder = DriveApp.getFolderById(parentFolderId);
  var files = parentFolder.getFiles();

  var fileTypeFolders = {
    'application/pdf': createOrGetFolder('PDFs', parentFolder),
    'image/jpeg': createOrGetFolder('Images', parentFolder),
    'application/vnd.google-apps.spreadsheet': createOrGetFolder('Spreadsheets', parentFolder),
  };

  while (files.hasNext()) {
    var file = files.next();
    var fileType = file.getMimeType();
    var targetFolder = fileTypeFolders[fileType];
    if (targetFolder) file.moveTo(targetFolder);
  }
}

function createOrGetFolder(folderName, parentFolder) {
  var folders = parentFolder.getFoldersByName(folderName);
  if (folders.hasNext()) return folders.next();
  return parentFolder.createFolder(folderName);
}
                                    

This script organizes files in a Google Drive folder into subfolders based on their file types. You can customize the rules to suit your specific file categorization needs.

Example 2 : Organizing Files by Date

You can also organize files by their creation or modification date. This script moves files into folders named by month and year.

 
function organizeFilesByDate() {
  var folder = DriveApp.getFolderById('YOUR_FOLDER_ID'); // Replace with your folder ID
  var files = folder.getFiles();
  
  while (files.hasNext()) {
    var file = files.next();
    var date = new Date(file.getDateCreated());
    var folderName = getFolderName(date);
    var targetFolderId = getOrCreateFolderId(folderName);
    
    var targetFolder = DriveApp.getFolderById(targetFolderId);
    file.moveTo(targetFolder);
  }
}

function getFolderName(date) {
  var month = date.getMonth() + 1; // Months are zero-based
  var year = date.getFullYear();
  return Utilities.formatString('%d-%02d', year, month); // Format as YYYY-MM
}

function getOrCreateFolderId(folderName) {
  var folders = DriveApp.getFoldersByName(folderName);
  
  if (folders.hasNext()) {
    return folders.next().getId();
  } else {
    var newFolder = DriveApp.createFolder(folderName);
    return newFolder.getId();
  }
}  

Explanation:
organizeFilesByDate Function: Moves files into folders based on their creation date.
getFolderName Function: Formats the folder name as "YYYY-MM."
getOrCreateFolderId Function: Checks if the folder exists or creates it if it doesn’t..

Example 3: Organize Files by User

This script sorts files in a folder based on the owner of the files. It creates a subfolder for each user and moves their files into these folders.

function organizeFilesByUser() {
  var parentFolder = DriveApp.getFolderById('YOUR_PARENT_FOLDER_ID'); // Replace with your parent folder ID
  var files = parentFolder.getFiles();
  
  var userFolders = {};
  
  while (files.hasNext()) {
    var file = files.next();
    var ownerEmail = file.getOwner().getEmail();
    
    if (!userFolders[ownerEmail]) {
      userFolders[ownerEmail] = createOrGetFolder(parentFolder, ownerEmail);
    }
    
    var targetFolder = userFolders[ownerEmail];
    file.moveTo(targetFolder);
  }
}

function createOrGetFolder(parentFolder, folderName) {
  var folders = parentFolder.getFoldersByName(folderName);
  
  if (folders.hasNext()) {
    return folders.next();
  } else {
    return parentFolder.createFolder(folderName);
  }
}
                            

Explanation:
organizeFilesByUser Function: Moves files into subfolders named after their owners' email addresses.
createOrGetFolder Function: Creates a new folder if it doesn’t exist or retrieves the existing one.

Example 4: Move Files Based on Keywords in File Names

This script moves files into folders based on keywords found in their file names.

function organizeFilesByKeyword() {
  var sourceFolder = DriveApp.getFolderById('YOUR_SOURCE_FOLDER_ID'); // Replace with your source folder ID
  var files = sourceFolder.getFiles();
  
  var keywordFolders = {
    'Report': 'REPORTS_FOLDER_ID', // Replace with actual folder IDs
    'Invoice': 'INVOICES_FOLDER_ID',
    'Meeting': 'MEETINGS_FOLDER_ID'
    // Add more keywords and folder IDs as needed
  };
  
  while (files.hasNext()) {
    var file = files.next();
    var fileName = file.getName();
    
    for (var keyword in keywordFolders) {
      if (fileName.includes(keyword)) {
        var targetFolder = DriveApp.getFolderById(keywordFolders[keyword]);
        file.moveTo(targetFolder);
        break;
      }
    }
  }
}                 

Explanation:
organizeFilesByKeyword Function: Moves files into folders based on keywords in their names.
keywordFolders Object: Maps keywords to folder IDs. Replace with your actual folder IDs.

Example 5: Consolidate Files from Multiple Folders into One

This script consolidates files from multiple folders into a single folder.

function consolidateFiles() {
  var sourceFolderIds = ['SOURCE_FOLDER_ID_1', 'SOURCE_FOLDER_ID_2']; // Replace with your source folder IDs
  var targetFolder = DriveApp.getFolderById('TARGET_FOLDER_ID'); // Replace with your target folder ID
  
  sourceFolderIds.forEach(function(folderId) {
    var sourceFolder = DriveApp.getFolderById(folderId);
    var files = sourceFolder.getFiles();
    
    while (files.hasNext()) {
      var file = files.next();
      file.moveTo(targetFolder);
    }
  });
}        

Explanation:
consolidateFiles Function: Moves all files from multiple source folders into a single target folder.

Conclusion

With Google Apps Script, you can automate and enhance your Google Drive experience by creating custom scripts to organize and manage your files and folders. Whether it's for personal use, project management, or team collaboration, the possibilities are endless.

Start automating your Google Drive today and take control of your file organization with the power of Apps Script!

Tips and Tricks

How to Create QR code using google sheet formula

How to Create QR code using google sheet formula

Dynamically generate QR Code with the help of a little formula.


Read More
How to Convert Column Index to Column Letter

How to Convert Column Index to Column Letter

Converting Column Index to Column Letter in Google Sheets using Google Apps Script


Read More
How to Create Google Forms with Apps Script

How to Create Google Forms with Apps Script

Creating Custom Google Forms with Apps Script Code


Read More
How to Automatically Update Google Calendar

How to Automatically Update Google Calendar

Automatically Update Google Calendar Events with Apps Script


Read More
How to Automate Google Drive

How to Automate Google Drive

Automating Google Drive: Organizing Files and Folders with Apps Script


Read More
How to Create a Google Apps Script Library

How to Create a Google Apps Script Library

Creating a Google Apps Script Library: Reusable Code and Functions


Read More

Start Your Project Now

90

Projects Completed

120

Happy Clients

5

Decoration Awards

240

Coffee Music