Search code examples
javascriptgoogle-apps-scriptgoogle-workspace-add-ons

Trying to get folder path through file id using appscript


I am pulling a drive activity report using GCP/GAMadv which gives me file IDs of various users in our workspace domain on a google sheet. My goal is to find the folder path of these files using file IDs. I am using appscript to get to that. Here is the code that I am running so far.

function getFolderPath(fileID, folderPath =""){
  var sheetID = "1YfZgkLvAnPj7kOIQOVkcXeJgnh-KTecMn6er1a0elkk"
  var sheet = SpreadsheetApp.openById(sheetID)
  // var file = sheet.Files.get(fileID)
  var parent = Drive.Files.get(fileID);
  console.log(parent)
  // console.log(file)
  var parentElement = parent.items[0]

  console.log(parentElement)
  // var parentElement = parent[0]

  var parentFile = Drive.Files.get(parent.id);
  var parentPath = parentFile.title;

  if (parent.isRoot)
  return "/" + folderPath;
  else {
    return getFolderPath(
      parentFile.id,
      parentPath + "/" + folderPath
    );
  }
}

Looks like this is returning ALL the files we have in our drive rather than the ones on the sheet. Help would be greatly appreciated! Thanks.


Solution

  • Folder Path from Id

    function getFolderPathFromId(id="fileid") {
      try {
        var file = DriveApp.getFileById(id)
        var pA = [];
        pA.push(file.getName());
        var folder = file.getParents();
        while (folder.hasNext()) {
          var f = folder.next();
          pA.push(f.getName());
          folder = f.getParents()
        }
        var r = pA.reverse().slice(0,-1).join(' / ');
      }
      catch (e) {
        return e;
      }
      Logger.log(r);
      return r;
    }