I want to know how to find out the top level directory parent of a file (which resides under "My Drive"). Files are stored under multi-level sub-folders.

Since I have the same file stored in multiple places, I want to make sure that the source of the file that I am picking up is the right one. I have made a really dirty hack, which is time consuming which looks like this:

function start() {
    var files = DriveApp.searchFiles("(title contains 'Worksheet')");
    while (files.hasNext()) {
      var file = files.next();
      var fileName = file.getName();
      var whichParents = getAllParents(file);
      // process whichParents to use indexOf to look for a substring in retStr and move forward.

function getAllParents(file) {
  var retStr="";
    var folder;
    var parents = file.getParents();
    while(1) {
      while (parents.hasNext()) {
      var parent = parents.next();
      retStr = retStr + parent.getName() + "->";
      if(parent.getName() == "My Drive")
        throw Exception;
      parents = folder.getParents();
    return retStr;    

I have looked through StackExchange for quite some time to figure out why an exception is generated, to no avail. Appreciate any help on this!

  • Asking for "best way" makes the question opinion-based specially if there isn't described what means "best". Commented May 19, 2020 at 17:15
  • From: Create pointers to any file or folder in Google Drive with shortcuts : "After September 30, 2020, all files already living in multiple locations in My Drive will gradually be migrated to shortcuts." Commented May 19, 2020 at 17:18
  • Why do your code include a while(1)? This will cause an error. Is that the exception that you mentioned? Commented May 19, 2020 at 17:22
  • I used while(1) to keep a variable depth of the directory structure. I was relying on throwing exceptions when there were no more folders to go in. There was no exception which was getting generated for this while loop. Commented May 20, 2020 at 3:49

1 Answer 1


Found a similar solution, which kind of works: https://gist.github.com/mesgarpour/07317e81e9ee2b3f1699

One more: https://gist.github.com/hubgit/3755293

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.