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 :
- 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:
Successful
1 2 3 4 |
{ "id":"3oij4i4_ksjfoi4oghosoi1-df9sfdjoi21slfdjoeijripe", "error":false }; |
Error
1 2 3 4 5 |
{ "id":false, "error":"There is more than one parent folder: Logo for file Yagisanatode.png" }; |
getFileByName()
reports the following errors:
- If no parent folder name is given and there are more than one file with the same file name.
- There is more than one parent folder and file combination with the same name.
- There are multiple files with the same name but none are in the folder parent name provided.
- No file with the file name provided exists.
Continue reading “Google Apps Script: Get File By Name – With Optional Parent Folder Crosscheck”