One of my recent projects in Google Apps Script required me to search for a file by name and get its ID. This can be problematic in Google Drive because you can have multiple files of the same name in multiple locations. My solution was to also check the file’s parent folder name as well.
I created a function getFileByName() to handle this. The function takes the following parameters:
fileName – The name of the file you are looking for. (required)
fileInFolder – The parent folder of the file you are searching for. (optional)
The file path would look a little something like this:
getFileByName() returns an object containing :
the ID of the file if the file exists or false if it does not.
the ERROR if there is an error or false if there is not.
The returned object would look like the following:
Unfortunately, I could not simply change the last folder name from say, Unit 4 Report to Q4 Unit 4 Report 2018 so it is easily searchable and unique. The other problem is that there are other Unit 4 Reports in other years and quarters so I did not want to accidentally call them instead of the exact one I wanted.
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.
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.