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.
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
/* * ****Get File By Name*** * *param 1: File Name *param 2: Parent Folder of File (optional) * *returns: Dictionary of file "id" and "error" message {"id": ,"error": } * -if there is no error, "id" returns file id and "error" returns false * -if there is an error, "id" returns false and "error" returns type of error as a string for user to display or log. */ function getFileByName(fileName, fileInFolder){ var filecount = 0; var dupFileArray = []; var folderID = ""; var files = DriveApp.getFilesByName(fileName); while(files.hasNext()){ var file = files.next(); dupFileArray.push(file.getId()); filecount++; }; if(filecount > 1){ if(typeof fileInFolder === 'undefined'){ folderID = {"id":false,"error":"More than one file with name: "+fileName+". \nTry adding the file's folder name as a reference in Argument 2 of this function."} }else{ //iterate through list of files with the same name for(fl = 0; fl < dupFileArray.length; fl++){ var activeFile = DriveApp.getFileById(dupFileArray[fl]); var folders = activeFile.getParents(); var folder = "" var foldercount = 0; //Get the folder name for each file while(folders.hasNext()){ folder = folders.next().getName(); foldercount++; }; if(folder === fileInFolder && foldercount > 1){ folderID = {"id":false,"error":"There is more than one parent folder: "+fileInFolder+" for file "+fileName} }; if(folder === fileInFolder){ folderID = {"id":dupFileArray[fl],"error":false}; }else{ folderID = {"id":false,"error":"There are multiple files named: "+fileName+". \nBut none of them are in folder, "+fileInFolder} }; }; }; }else if(filecount === 0){ folderID = {"id":false,"error":"No file in your drive exists with name: "+fileName}; }else{ //IF there is only 1 file with fileName folderID = {"id":dupFileArray[0],"error":false}; }; return folderID; }; |
An Example
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
// ****EXAMPLE**** //My arguments for the function var myFileName = "YagisanatodeLong.png"; var myFileParentFolderName = "Logo"; //Run the function var getFileID = getFileByName(myFileName, myFileParentFolderName); //Check if folder exists if(getFileID.id === false){ //if file cannot be accurately found. Logger.log(getFileID.error); //alert or log error. Give option to try another FileName }else{ // If the file ID exists then proceed with the program. Logger.log(getFileID.id); }; /* * ****Get File By Name*** * *param 1: File Name *param 2: Parent Folder of File (optional) * *returns: Dictionary of file "id" and "error" message {"id": ,"error": } * -if there is no error, "id" returns file id and "error" returns false * -if there is an error, "id" returns false and "error" returns type of error as a string for user to display or log. */ function getFileByName(fileName, fileInFolder){ var filecount = 0; var dupFileArray = []; var folderID = ""; var files = DriveApp.getFilesByName(fileName); while(files.hasNext()){ var file = files.next(); dupFileArray.push(file.getId()); filecount++; }; if(filecount > 1){ if(typeof fileInFolder === 'undefined'){ folderID = {"id":false,"error":"More than one file with name: "+fileName+". \nTry adding the file's folder name as a reference in Argument 2 of this function."} }else{ //iterate through list of files with the same name for(fl = 0; fl < dupFileArray.length; fl++){ var activeFile = DriveApp.getFileById(dupFileArray[fl]); var folders = activeFile.getParents(); var folder = "" var foldercount = 0; //Get the folder name for each file while(folders.hasNext()){ folder = folders.next().getName(); foldercount++; }; if(folder === fileInFolder && foldercount > 1){ folderID = {"id":false,"error":"There is more than one parent folder: "+fileInFolder+" for file "+fileName} }; if(folder === fileInFolder){ folderID = {"id":dupFileArray[fl],"error":false}; }else{ folderID = {"id":false,"error":"There are multiple files named: "+fileName+". \nBut none of them are in folder, "+fileInFolder} }; }; }; }else if(filecount === 0){ folderID = {"id":false,"error":"No file in your drive exists with name: "+fileName}; }else{ //IF there is only 1 file with fileName folderID = {"id":dupFileArray[0],"error":false}; }; return folderID; }; |
The result of this example would be:
Logs
[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.
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.
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?
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.
~Yagi
Hi Yagi,
I did not understand the following piece of code;
//Get the folder name for each file
while(folders.hasNext()){
folder = folders.next().getName();
foldercount++;
};
Won’t we get the name of the last folder which might match with fileInFolder?
Hi sheelooxl,
Yeap. You are correct. It should get the last value in the list of any potential parent folders for the file. The example was only designed to compare one folder. If there are more, it will throw a warning in the lines 45 and 46 code. So the lazy-man option here was just to record the last value in the list of all parent folders of the file and if there were more than one folder, we would record it in the
foldercount
variable and that would trigger an error message.A little context. Back in 2018 when this was written, Google Drive was only flirting with creating multiple directory locations for the same file so it was just a cursory check.
I think also to the code I was writing needed the file to have one folder locations; the reason for which has long since escaped me.
Today, I would write things a little differently 🙂.
Great question.
Happy coding!