Gsuz
Gsuz

Reputation: 353

Specifying nested folder directly?

So I use this code to specify the folder in google drive that i want but I'm hoping there is a better way?

var folders = DriveApp.searchFolders("title contains '"+Values[3]+"' and 'jlfXPTjmRlS2dQf5SS3RaUWM....' in parents");
    while (folders.hasNext()) {
      var folder = folders.next();
      var folder = folder.getId();
      var subfolders = DriveApp.searchFolders("title contains '"+Values[4]+"' and '"+folder+"' in parents");
      while (subfolders.hasNext()) {
        var subfolder = subfolders.next(); // got My folder here!
        // *Actions*
}}

The folder i want to specify is nested as such:

/shared folder(known by id)/subfolder(known by name)/subfolder(known by name)

My guess is this should be done with DocsList.getFolder(path) but I can't get it to work. Also I need this code to be compatible for collaborators that I have shared the base folder with.

Upvotes: 3

Views: 1328

Answers (1)

Serge insas
Serge insas

Reputation: 46812

Have a look at Mogsdad's answer in this post, I think it should help you: Migrating from DocsList to DriveApp?

Code is reproduced below, it does not need a lot of explanations : use the path as parameter and get a folder object as return.

 function getFolderByPath(path) { 
    var parts = path.split("/");    
    if (parts[0] == '') parts.shift(); // Did path start at root, '/'?

    var folder = DriveApp.getRootFolder();
    for (var i = 0; i < parts.length; i++) { 
      var result = folder.getFoldersByName(parts[i]); 
      if (result.hasNext()) {
        folder = result.next(); 
       } else { 
       return null;
       } 
     } 
    return folder;
  }

Upvotes: 4

Related Questions