Google Apps Script – DriveApp
Well, it’s a rainy day here travelling in Romania, so time for a post.
When creating a Google Apps Script’s I often find I am creating new folders and files in specific locations on Google Drive after, say, generating a report or something.
A Note on Folders in Google Drive
All files and folders in Google Drive are allocated a unique key that identifies them.
The file location and all the data about the file are mapped to this ID. This means you can have as many folders or files with the same name even in the same directory without a duplicate error being thrown because they all have their own unique ID for their URL.
Getting Started
More often than not, I know the parent folder that I want to put my subfolders in. This means I can get the parent folder’s ID and use that as my starting point to add subfolders. To do this we use the DriveApp class.
Below are three useful functions for creating folders.
- Simple – Create a folder under the Parent folder ID – Duplicates are not checked and there can be multiple subfolders with the same name but all have their own unique id.
- Medium – Create a folder only if that folder name does not exist in the Parent folder – No folder is created if the folder already exists.
- Hard-ish – Create a folder. If the name exists, add a counter to the name – If the file already exists then add a counter to the end of the file name.
All the functions will take two arguments: folderID
– the unique id of the parent folder and folderName
– the name you want to call your new folder.
The start()
function will simply grab the two variables for the folderID
and folderName
and run the folder creation function. This is to simulate using the functions in your code.
Feel free to read what you need. I try and write these for a wide range of coding skill in mind.
Simple – Create a folder under the Parent folder ID
Here, we are going to simply add a folder. It doesn’t matter if the folder already exists, we’ll just create another one.
The Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//Creates a folder as a child of the Parent folder with the ID: FOLDER_ID function createFolderBasic(folderID, folderName) { var folder = DriveApp.getFolderById(folderID); var newFolder = folder.createFolder(folderName); return newFolder.getId(); }; function start(){ //Add your own folder ID here: var FOLDER_ID = '130KbplcZX1AzJUD3vq2uAaRXmN-PaTuK'; //Add the name of your folder here: var NEW_FOLDER_NAME = "The New Folder"; var myFolderID = createFolderBasic(FOLDER_ID, NEW_FOLDER_NAME); Logger.log(myFolderID); }; |
When the start()
function is run on line 8 it creates a variable for the FOLDER_ID and the NEW_FOLDER_NAME. On line 14 we add these two variables to the arguments for the function createFolderBasic
.
createFolderBasic(folderID, folderName)
On line 3 of this function we find the parent folder we want to add the subfolder to. We do this by calling the DriveApp class with the getFolderById()
method inputting the folderID
here. We will keep this in the variable, folder
, to be used on the next line.
Line 4 then creates the newFolder
by getting the folder variable and applying the createFolder
method to it with the argument folderName
.
Finally, on line 5 we return the newFolder
by id so we can use it later. We have logged the folder ID in the start()
function so we know it is working.
Each time you run this code, you will get a new file with the same file name but a different ID in the URL.
Medium – Create a folder only if that folder name does not exist in the Parent folder
In this function, we will only create a folder if the folder does not exist. We will return the folder id of either the new folder or the existing folder.
The code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
//Create folder if does not exists only function createFolder(folderID, folderName){ var parentFolder = DriveApp.getFolderById(folderID); var subFolders = parentFolder.getFolders(); var doesntExists = true; var newFolder = ''; // Check if folder already exists. while(subFolders.hasNext()){ var folder = subFolders.next(); //If the name exists return the id of the folder if(folder.getName() === folderName){ doesntExists = false; newFolder = folder; return newFolder.getId(); }; }; //If the name doesn't exists, then create a new folder if(doesntExists == true){ //If the file doesn't exists newFolder = parentFolder.createFolder(folderName); return newFolder.getId(); }; }; function start(){ //Add your own folder ID here: var FOLDER_ID = '130KbplcZX1AzJUD3vq2uAaRXmN-PaTuK'; //Add the name of your folder here: var NEW_FOLDER_NAME = "The New Folder"; var myFolderID = createFolder(FOLDER_ID, NEW_FOLDER_NAME); Logger.log(myFolderID); }; |
In this example, the start() function is the same. The only change is the function name that will be called is createFolder()
on line 33.
createFolder()
First, on line 3 we get the folder ID of the parentFolder
using DriveApp.getFolderById(folderID)
. On the next line, we use this parentFolder
variable to get the child folders in that directory with the getFolders()
method – more on this in a moment. We will put this generator of folders in the subFolders
variable.
Next, on line 5 we create the doesntExists
variable and set it to true. This basically says that if the file with the name we have set does not exist then we will say that the statement is true
.
the getFolders
() method creates a generator listing all the folder in that directory. So we will need to iterate through this generator of folders to check if a folder with the folderName
we want to add. Fortunately getFolders()
takes two further methods – hasNext()
which, in conjunction with a while
loop states that while there is another folder to look at in the list, do something (line 9).
While in the erh… while
loop we want to look at each folder so we create the variable folder to look at the next()
folder in the loop.
On line 13, we want to check if the file with the same name as our folderName
exists. If it does we change our doesntExists
variable to false. We then make our newFolder
variable the name of the folder we have found in the loop that contains a match for the folderName
and returns the id for this folder so we can use it in our code at a later time.
Alternative if we can’t find the file in our subFolder
generator (line 20), then we use the createFolder(folderName)
method and then return the newFolder
ID.
This time, even if we run the script it will only generate a new folder if the folder does not exist in the Parent folder.
Hard-ish – Create a folder. If the name exists, add a counter to the name
This function is a little bit like how Windows deals with multiple file names. The function will create a folder even if the folder exists, but if the folder does exist then it will rename the folder with a counter at the end. For example, say we want to create a folder with the name: banana
. If that name already exists then we will rename it to: banana(1)
.
The problem is, what if we already have a file with the name banana(1)
? What if we have a file with the name: banana(2)
? We will have to deal with this in our code.
Let’s take a look:
The Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
//Create folder if already exists change the file name function createFolderWithChange(folderID, folderName){ var parentFolder = DriveApp.getFolderById(folderID); var subFolders = parentFolder.getFolders(); var exists = false; var newFolder = ''; var folderArray = [] // Creat an array from the generator while(subFolders.hasNext()){ folderArray.push(subFolders.next().toString()); }; //If a folder with the file name exists, check if it also has a file + number //then create a file name with the next available nummber in the list. if(folderArray.indexOf(folderName) !== -1.0){ exists = true var num = 1 while(exists === true){ if(folderArray.indexOf(folderName+"("+num+")") !== -1.0){ num += 1 }else{ exists = false newFolder = parentFolder.createFolder(folderName+"("+num+")"); return newFolder.getId(); }; }; }else{ newFolder = parentFolder.createFolder(folderName); return newFolder.getId(); }; }; function start(){ //Add your own folder ID here: var FOLDER_ID = '130KbplcZX1AzJUD3vq2uAaRXmN-PaTuK'; //Add the name of your folder here: var NEW_FOLDER_NAME = "The New Folder"; var myFolderID = createFolderWithChange(FOLDER_ID, NEW_FOLDER_NAME); Logger.log(myFolderID); }; |
Nothing changes in our start()
function except that we use the new function name createFolderWithChange(FOLDER_ID, NEW_FOLDER_NAME)
.
createFolderWithChange()
We start this function by setting some variables.
Again we find the parentFolder
with DriveApp's getFolderById(folderID)
(line 3). We then get the subFolders
as a generator. Create an exists
variable that is set to false (thought I’d change it up a bit 😀 Yagi, you so kwazy!) . Set an empty newFolder
variable to put our new folder ID in once we get it. This time we will also add the folderArray
variable to store our list of folders in our parent folder (yeah, we gotta do it a little different this time).
Line 10 starts our iteration through our subFolders
generator. It essentially says that while there is another folder in the list (hasNext()
)then get the next()
folder and do something with it. On line 11 we push the folder name to the folderArray
variable. We will need to convert these to a string so that we can compare them against our folderName
.
In our next step starting on line 15 we want to do three things: 1. If our folderName
is in our folderArray
list then, 2. check if our folderName
also exists with a number counter and 3. check each counter and then add the next consecutive counter as the newFolder
. For example, if our folderName
, “The New Folder” exists then search the array for “The New Folder(1)”, “The New Folder(2)”, etc until we run out and add the file “The New Folder(#)”.
On line 15 we use the indexOf
method to determine if the folder exists with the folderName
. If it doesn’t we move to line 27 and simply create a newFolder
and return the folder ID for us to work with. If it does exist, we then change exists
to true
, because, you know, it now is and then set the counter, num
that we will use at the end of our folderName
(lines 16 & 17).
Next, we run another while loop which states, while the folderName
exists (or is true), then do something (line 18). That something is another if statement that asks if the folderName
plus the num
counter is in the folderArray
simply add 1 to num
.
Alternatively, if there is no folder with the same name as folderName
plus num
(line 21), set exists
to false
(line 22) and create a newFolder
with the next num
in the list(line 23). We then return the id of the newFolder
for us to use in our code (line 24).
Conclusion
So there you have it. Three approaches to use Google Apps Script’s DriveApp to create folders when you have the id of the Parent Folder. Give it a try.
More on DriveApp:
- Google Apps Script – How to Find the Folder ID of a Non-Unique Folder Using File Path Names
Need help with Google Workspace development?
My team of experts can help you with all of your needs, from custom app development to integrations and security. We have a proven track record of success in helping businesses of all sizes get the most out of Google Workspace.
Schedule a free consultation today to discuss your needs and get started or learn more about our services here.
This was super helpful. There is a bug in line 20 of the Medium example, should be: if(doesntExists == true){
Great find. Updated.
Thanks, Paul.
Thank you so much for putting this together. Very clear and straightforward.
Hi Michael,
I am glad you found this helpful.
Happy coding!
~Yagi
hi ! Is it possible to create a folder with variable id by using your script? For exemple, I want function start(IdParentFolder,FolderName) and call this function directly in a spreedsheet, to create different folder for different parameters.
I tried, it looked easy but It seems to have an issue with “DriveApp”.
function start(IdParentFolder,FolderName){
//Add your own folder ID here:
var FOLDER_ID = IdParentFolder;
//Add the name of your folder here:
var NEW_FOLDER_NAME = FolderName;
var myFolderID = createFolderBasic(FOLDER_ID, NEW_FOLDER_NAME);
Logger.log(myFolderID);
};
Hi Mathieu,
There are some limitations about what a Custom Function can do. They are mostly designed to retrieve external data to be used in your Google Sheets formula, but not edit other documents.
You can however, use a button or menu item to run a process with details in your Google Sheet that could create and manager drive folders.
~Yagi