Google Apps Script: Get File By Name – With Optional Parent Folder Crosscheck

Google Apps Script:  DriveApp

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:

.../fileInFolder/fileName

getFileByName() returns an object containing :

  1.  the ID of the file if the file exists or false if it does not.
  2. the ERROR if there is an error or false if there is not. 

The returned object would look like the following:

Successful

Error

getFileByName() reports the following errors:

  1. If no parent folder name is given and there are more than one file with the same file name. 
  2. There is more than one parent folder and file combination with the same name.
  3. There are multiple files with the same name but none are in the folder parent name provided.
  4. No file with the file name provided exists.

Continue reading “Google Apps Script: Get File By Name – With Optional Parent Folder Crosscheck”