Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active Dec 6, 2020
Embed
What would you like to do?
Achieving Search of Files by 'is:unorganized owner:me' using Google Apps Script

Achieving Search of Files by 'is:unorganized owner:me' using Google Apps Script

This is a sample script for achieving the search of files by is:unorganized owner:me using Google Apps Script.

In the current stage, unfortunately, the files cannot be directly retrieved by searching is:unorganized owner:me with Drive API and Drive service. So as the current workaround, all files are retrieved using the method of "Files: list" of Drive API with 'me' in owners and trashed = false, and the file list is retrieved from all file list using a script.

Sample script

Before you use this script, please enable Drive API at Advanced Google services. And please run main() function.

// Retrieve the file list by searching with "is:unorganized owner:me".
function getFileList(token) {
  const fields = decodeURIComponent(
    "nextPageToken,files(name,id,mimeType,parents)"
  );
  const q = decodeURIComponent("'me' in owners and trashed = false");
  let allFiles = [];
  let pageToken = "";
  do {
    const res = UrlFetchApp.fetch(
      `https://www.googleapis.com/drive/v3/files?pageSize=1000&fields=${fields}&q=${q}&pageToken=${pageToken}`,
      { headers: { authorization: `Bearer ${token}` } }
    );
    const obj = JSON.parse(res);
    allFiles = allFiles.concat(obj.files);
    pageToken = obj.nextPageToken;
  } while (pageToken);
  return allFiles.filter(({ parents }) => !parents);
}

// Please run this function.
function main() {
  const token = ScriptApp.getOAuthToken();
  const fileList = getFileList(token);
  console.log(fileList.length);
  console.log(fileList);

  // DriveApp.getFiles(); // This is used for automatically adding a scope of "https://www.googleapis.com/auth/drive.readonly".
}
  • In order to retrieve all files, when Drive API v3 using UrlFetchApp is used, the process cost is much lowere than that using Drive API of Advanced Google services. So I used Drive API v3 using UrlFetchApp instead of Drive API of Advanced Google services.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment