Search code examples
google-apps-scriptgoogle-drive-apigoogle-workspacegoogle-drive-shared-drive

How to create a list of all folders in a shared goggle drive folder


I'm trying to create a listing of all my google drive folders and I have the following script and a link to the question where I got the script from. I'm just not sure how to implement it. I put the Drive ID in line 6 and then ran it and got this error; Can anyone tell me where I'm going wrong?

List every file and folder of a shared drive in a spreadsheet with Apps Script

11:08:37 AM Error
ReferenceError: gobj is not defined getFoldersInASharedFolder @ Folder Listing.gs:12

This is the script

function getFoldersInASharedFolder() {
  let tr = [];
  let token = '';
  let page = 0;
  do {
    let r = Drive.Files.list({ corpora: 'drive', includeItemsFromAllDrives: true, supportsTeamDrive: true, supportsAllDrives: true, driveId: "???", pageToken: token,q: "mimeType = 'application/vnd.google-apps.folder'" });
    let obj = JSON.parse(r);
    tr.push(obj)
    token = obj.nextPageToken
  } while (token != null)

  let folder = DriveApp.getFolderById(gobj.globals.testfolderid);
  folder.createFile(`SharedDriveList ${Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MM/dd/yyyy HH:mm:ss")}`, JSON.stringify(tr), MimeType.PLAIN_TEXT);

  let html = '<style>td,th{border:1px solid black;font-size: 16px;}</style><table><tr><th>Title</th><th>Id</th><th>Path</th></tr>';
  tr.forEach((o, i) => {
    o.items.forEach(item => {
      if (item.mimeType = "application/vnd.google-apps.folder") {
        html += `<tr><td>${item.title}</td><td>${item.id}</td><td>${getPathAllDrivesFromId(item.id)}</td></tr>`;
      }
    })
  });
  html += '</table><input type="button" value="exit" onclick="google.script.host.close()" />';
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html).setHeight(500).setWidth(1200), `Folders in: ${JSON.parse(Drive.Drives.get("driveid")).name}`);
}

Solution

  • The error message occurs because

    let folder = DriveApp.getFolderById(gobj.globals.testfolderid);
    

    use the a nested property of gobj as parameter but gobj was not declared.

    You can fix this error either by properly declaring gobj or by replacing gobj.globals.testfolderid by the folder id (properly set as a string).