Retrieving Files and Folders without Parents in Google Drive

Gists

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

 Share!