Search code examples
javascriptsearchgoogle-apps-scriptgoogle-drive-apidirectory-structure

Search through structure of folders


Using Google Apps Script I need to search through a structure of folders in Google Drive. The thing is that I don't know how many levels of subfolders will be inside the main folder (take a look at the image). I'll always be looking for "file-2" but there will be a lot of "file-2" and I need to find all of them.

I don't know the name nor the ID of the subfolders.

I don't know the ID of the files "file-2" that I need to search.

I only know that there will be a main folder and I need to search for all of the files "file-2" inside.


Solution

  • You don't need to iterate all folders ans subfolders, DriveApp has a searchFiles(params) method that will return all the files with that name, no matter where they are.

    example :

     var files = DriveApp.searchFiles(
         'title contains "file-2"');
     while (files.hasNext()) {
       var file = files.next();
       Logger.log(file.getName());// file is a file object, it has methods to get parent folders if this info is useful... see same doc + links
     }