How to search for Folder using Google Apps Scripts
the search files method only return files. According to GAS API this methos is used for "Gets a collection of all files that are children of the current folder and match the given search criteria." See it here.
To find a folder by it's name use the code bellow:
function getFolders(folderName)
{
var folders = DriveApp.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
if(folderName == folder.getName()) {
return folder;
}
}
return null;
}
Andrew
Updated on June 15, 2022Comments
-
Andrew almost 2 years
Have I made a simple mistake or can we not search for folders using .searchFiles method on DriveApp? I have a more complex search parameter but I've simplified it for this example.
function getFolders() { var searchParams = 'mimeType = "application/vnd.google-apps.folder"'; var searchFiles = DriveApp.searchFiles(searchParams); if (searchFiles.hasNext()) { // Do Something } else { // Error Logger.log("No folders found"); } }
The documentation states it returns a FileIterator but refers to the Google Drive SDK for further information https://developers.google.com/apps-script/reference/drive/drive-app#searchFiles(String)
In the search parameters here, we can specify if it's a folder or not https://developers.google.com/drive/search-parameters
Are there options for searching for a folder name?
-
Rubén about 4 yearsDocList is deprecated.