Home > Enterprise >  JavaScript - Iterate over shared drives to get file by input string (Google Apps Script)
JavaScript - Iterate over shared drives to get file by input string (Google Apps Script)

Time:05-27

I have 4 shared drives with unique files named 00000001.xml, 00000002.xml ... (like IDs). Every drive has ~350k files.

So, my question is, if I input e.g. 08475398 as an ID, what would be the faster way to iterate over drives?

CodePudding user response:

I believe your goal is as follows.

  • You have 4 shared drives.

  • You have the files of the filenames like 00000001.xml, 00000002.xml,,,. 00000001 and 00000002 are the IDs.

  • You want to search the files using the ID.

    So, my question is, if I input e.g. 08475398 as an ID, what would be the faster way to iterate over drives?

  • You want to achieve this using Google Apps Script.

In this case, how about the following sample script?

Sample script:

This script uses Drive API. So, please enable Drive API at Advanced Google services. And, please set the ID you want to search to id. And, run the script.

And, please set 4 drive Ids you want to search.

function myFunction() {
  const id = "08475398"; // Please set the ID.
  const driveIds = ["###driveId1###", "###driveId2###", "###driveId3###", "###driveId4###"]; // Please set 4 Drive IDs you want to search.

  const q = `title contains '${id}' and trashed = false`;
  const fields = "nextPageToken,items(id,title,driveId,mimeType)";
  let fileList = [];
  let pageToken = "";
  do {
    const { items, nextPageToken } = Drive.Files.list({ pageSize: 1000, corpora: "allDrives", includeItemsFromAllDrives: true, supportsAllDrives: true, q, fields, pageToken });
    if (items.length > 0) fileList = [...fileList, ...items];
    pageToken = nextPageToken;
  } while (pageToken);
  const res = fileList.filter(({driveId}) => driveIds.includes(driveId));
  console.log(res)
}
  • When this script is run, the files of the filenames including id are searched from all shared Drives that you can access and retrieved as a file list. And the retrieved file list is filtered using driveIds. As the sample, in this case, the file metadata of id,title,driveId,mimeType is retrieved. About the file metadata, please modify this for your actual situation.

  • If you want to access to the file using the retrieved file list, you can access it using the file ID.

Reference:

  • Related