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:


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:



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.

The Code

An Example

The result of this example would be: 


[18-10-04 21:59:33:127 PDT] keJCYO4cCwZhNvyprL63jDvfluwP0gLtV

You might also find this useful: 

Google Apps Script – How to Find the Folder ID of a Non-Unique Folder Using File Path Names

I hope you find it useful.


Looking to learn more about Google Apps Scripts in a more structured format? Udemy has some great courses that can get you from the basics to a real Google Apps Script pro! Got a more specific problem you need help with, but don’t have the time to develop the skills? Fiverr’s your best bet to find a skilled Google Apps Script professional to solve your problem quickly and cheaply. *

*The above affiliate links have been carefully researched to get you to what you specifically need. If you decide to click on one of these links it will cost you just the same as going to the site. If you decide to sign up, I just get a little pocket money to help pay for the costs of running this website.

2 thoughts on “Google Apps Script: Get File By Name – With Optional Parent Folder Crosscheck”

  1. If I understand your code correctly, I will need to specify the full name of the file for the file iterator to return true. What if I only vaguely remember the file name, e.g. I want to file files whose names contain ‘yagisana’? Do I have to get all the files and loop through them?

    1. Hi Trang,

      The searchFiles() method is proabably your best bet here with search query terms found here.

      I hope that helps.

      BTW. I like your webpage. Very elegant and Google Drive Search CLI App looks cool.


Leave a Reply