I currently have a Zapier process running that automatically creates 3 new files uploaded from a form into a folder in my Google Drive called "New Users". Each file is formatted as firstname_lastname-filename.ext but this is not good in terms of organization.
Instead, I would like to dynamically create a new folder labeled as firstname_lastname containing the 3 new files every time they come in with the same firstname_lastname, rather than having a generic "New Users" folder filled with hundreds or thousands of files.
Unfortunately I'm a pretty novice programmer, so I'm not quite sure how to go about this using Apps Script.
Any advice?
I've thought about something like:
var files = DriveApp.getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
if file.getName().includes("firstname_lastname") { // Check if a file name contains the string firstname_lastname
var folders = DriveApp.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
Logger.log(folder.getName());
if folder.getName().includes("firstname_lastname") { // Check if a folder exists with a name that contains the string firstname_lastname
makeCopy(file.getName(), folder.getName()) // if said folder exists, make a copy of the the file and move it to that folder
} else { // if said folder does not exist...
var newFolderName = file.getName() // let the newFolderName be the same name as the file (I know this isn't right if I want the folder name to be firstname_lastname without the actual uploaded file name plus extension)
createFolder(newFolderName); // then create a folder that has the name newFolderName
makeCopy(file.getName(), folder.getName(newFolderName)) // then make a copy of the file and put it into the folder
}
}
}
}
You may want to first establish your root folder, "New Users". I've created a snippet for the flow:
//New Users Folder
var rootFolder = DriveApp.getFolderById("FOLDER_ID");
function myFunction() {
var files = rootFolder.getFolders();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
if(file.getName() == fileuploadName){
//copy file if folder is existing
file.addFile(child)
}
else{
//create folder
var newFolder = rootFolder.addFolder(child);
newFolder.addFile(child)
}
}
Logger.log("Done")
}
This flow should be ok when you want to implement a dynamic creation of folder then migrate the files to a specific folder name.
Hope this helps.