I want to organize my Google Drive files automatically. Right now I have many files stored in one folder but I need them sorted into separate folders based on their names.
The files are .png and .pdf formats. I want a Google Apps Script that can read each filename, create a new folder using part of that filename, and move all files with matching prefixes into the correct folder no matter what file type they are.
I need the script to create folders called INV001234, INV001235, and INV001236. Then it should move all files that start with each number into the matching folder.
So all files starting with INV001234 would go into the INV001234 folder and so on. Can someone help me write this script?
I faced a similar scenario previously when needed to sort client files. A good approach is to first gather unique prefixes from filenames into a Set to avoid redundant folder creation. Then, cycle through the files to create folders in batch based on these prefixes. You can use file.getName().split('_')[0] to extract the prefix, create folders with parentFolder.createFolder(prefix), and finally, another loop can move files into their respective folders using file.moveTo(targetFolder). Remember to handle folder creation with try-catch blocks to manage cases where folders already exist. This method enhances efficiency by minimizing API calls.
Here’s a script that works great for this. Loop through your files once and handle folder creation plus file movement together - saves you from making tons of API calls. Start by grabbing the parent folder ID, then use getFiles() to go through each file. Pull the prefix with substring() up to the underscore, check if that folder exists with getFoldersByName(). No folder? Create it with createFolder(). Then just moveTo() to move the file. This processes everything in order and won’t break if you have duplicate folder names. Don’t forget error handling for files that don’t match your naming pattern.
i used a map to store folder refs - way faster than constantly searching for the same folders. first, grab all your files. then for each file, pull the prefix before the underscore and check if that folder exists in your map. if it doesn’t, create it and add it to the map. then just move the file. beats calling getFoldersByName every single time.