Andrew
Andrew

Reputation: 71

How to search for Folder using Google Apps Scripts

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?

Upvotes: 2

Views: 11839

Answers (2)

Andrew
Andrew

Reputation: 71

Ended up using DocsList instead of DriveApp

https://developers.google.com/apps-script/reference/docs-list/docs-list#getAllFolders()

The above solution by br araujo answers the original question, so I've marked it as the answer.

The issue with using DocsList is that the Folder type it returns is not compatible with DriveApp. To make them compatible we just pass the Id between function calls instead of objects.

Upvotes: -1

br araujo
br araujo

Reputation: 1872

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;
}

Upvotes: 4

Related Questions