Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created March 13, 2020 08:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/459089e678bad943f0f33e497e04c36f to your computer and use it in GitHub Desktop.
Save tanaikech/459089e678bad943f0f33e497e04c36f to your computer and use it in GitHub Desktop.
Retrieving Files and Folders without Parents in Google Drive

Retrieving Files and Folders without Parents in Google Drive

This is a sample script for retrieving the files and folders which have no parents in own Google Drive.

When you use this script, please enable Drive API at Advanced Google services.

Sample script

const myFunction = () => {
  const token = ScriptApp.getOAuthToken();
  const fields = decodeURIComponent(
    "nextPageToken,files(name,id,mimeType,parents)"
  );
  const q = decodeURIComponent("'me' in owners and trashed = false");
  let files = [];
  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);
    Array.prototype.push.apply(files, obj.files);
    pageToken = obj.nextPageToken;
  } while (pageToken);
  const result = files.filter(({ parents }) => !parents);
  console.log(result);
};

When you run the script, the files and folders which have no parents in own Google Drive are retrieved.

References

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