Skip to content

Instantly share code, notes, and snippets.

@FranciscoHV
Forked from tanaikech/submit.md
Created July 10, 2023 21:36
Show Gist options
  • Save FranciscoHV/75f399be9fc47dac1bb9e01baf2bdde2 to your computer and use it in GitHub Desktop.
Save FranciscoHV/75f399be9fc47dac1bb9e01baf2bdde2 to your computer and use it in GitHub Desktop.
Managing Shared Drive using Drive Service of Google Apps Script

Managing Shared Drive using Drive Service of Google Apps Script

When the method of "Files: list" in Drive API v3, the official document of includeItemsFromAllDrives and supportsAllDrives says as follows.

Deprecated - Whether both My Drive and shared drive items should be included in results. This parameter will only be effective until June 1, 2020. Afterwards shared drive items are included in the results. (Default: false)

Deprecated - Whether the requesting application supports both My Drives and shared drives. This parameter will only be effective until June 1, 2020. Afterwards all applications are assumed to support shared drives. (Default: false)

From this situation, I thought that Drive service might be able to manage the shared Drive from June 1, 2020. So I tested this as follows. As the results, I could confirm that now, the shared Drive got to be able to be managed by Drive service.

Retrieve file list:

const folderId = "###"; // Folder ID of the shared Drive.

const files = DriveApp.getFolderById(folderId).getFiles();
while (files.hasNext()) {
  const f = files.next();
  console.log(f.getName());
}
  • This worked.

Create file:

const folderId = "###"; // Folder ID of the shared Drive.

DriveApp.getFolderById(folderId).createFile(
  "sample.txt",
  "sample",
  MimeType.PLAIN_TEXT
);
  • This worked.

Retrieve file list including subfolder:

In this sample script, the file list of all files and folders including subfolders under specific folder are retrieved.

function myFunction() {
  const getFileList = (id, folders = []) => {
    const f = DriveApp.getFolderById(id);
    const fols = f.getFolders();
    let temp = [];
    while (fols.hasNext()) {
      const fol = fols.next();
      const files = fol.getFiles();
      let fileList = [];
      while (files.hasNext()) {
        const file = files.next();
        fileList.push({ name: file.getName(), id: file.getId() });
      }
      temp.push({
        name: fol.getName(),
        id: fol.getId(),
        parent: id,
        parentName: f.getName(),
        files: fileList,
      });
    }
    if (temp.length > 0) {
      folders.push(temp);
      temp.forEach((e) => getFileList(e.id, folders));
    }
    return folders;
  };

  const folderId = "###"; // Folder ID of the shared Drive.
  const res = getFileList(folderId);
  console.log(res);
}
  • This worked.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment