- I try to iterate between folders until I find the folder with the name Project and inside that folder keep iterating until I find the file with the name Test and that it is type spreadsheet.
- The first script if it finds the file but I want to specify I look inside the folders with the name Project to improve the performance of the script
- The second script I’m trying is not iterating, so it does not work because when I run it, it only finds the first folder and dont searching inside the others folders, Thanks for trying to help me. I hope that now it has given me to understand
From your this reply, I could understand as follows.
- You want to retrieve Spreadsheet with the filename of
Test
under the folder with the name ofProject
. You want to do this with low process cost.
If my understanding is correct, how about these sample scripts? Please choose from them for your situation. I think that there are several answers for your situation. So please think of this answer as one of them.
Pattern 1:
Flow:
- Retrieve files from filename of
Test
usinggetFilesByName()
. - Retrieve parent folders of each file using
getParents()
. - If the folder name is
Project
and the mimeType is Spreadsheet, it retrieves the file.
Sample script:
var fileName = "Test"; var folderName = "Project"; var files = DriveApp.getFilesByName(fileName); while (files.hasNext()) { var file = files.next(); var parents = file.getParents(); while (parents.hasNext()) { var parent = parents.next(); if (file.getMimeType() == MimeType.GOOGLE_SHEETS && parent.getName() == folderName) { // do something } } }
Pattern 2:
Flow:
- Retrieve folders from folder name of
Project
usinggetFoldersByName()
. - Retrieve files in each folders using
getFilesByName()
. - If the filename is
Test
and the mimeType is Spreadsheet, it retrieves the file.
Sample script:
var fileName = "Test"; var folderName = "Project"; var folders = DriveApp.getFoldersByName(folderName); while (folders.hasNext()) { var folder = folders.next(); var files = folder.getFilesByName(fileName); while (files.hasNext()) { var file = files.next(); if (file.getMimeType() == MimeType.GOOGLE_SHEETS && file.getName() == fileName) { // do something } } }
Pattern 3:
Flow:
- Retrieve folder IDs of folder name of
Project
usinggetFoldersByName()
. - Retrieve files with the parent folder of
Project
and the filename ofTest
and the mimeType of Spreadsheet usingsearchFiles()
.
Sample script:
var fileName = "Test"; var folderName = "Project"; var folders = DriveApp.getFoldersByName(folderName); var folderIds = []; while (folders.hasNext()) { folderIds.push(folders.next().getId()); } folderIds.forEach(function(id) { var params = "'" + id + "' in parents and title='" + fileName + "' and mimeType='" + MimeType.GOOGLE_SHEETS + "'"; var files = DriveApp.searchFiles(params); while (files.hasNext()) { var file = files.next(); // do something } });
References:
If these were not what you want, I’m sorry.