Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created October 19, 2022 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/2b9d86a7db01f72e88090116cb5fee1f to your computer and use it in GitHub Desktop.
Save tanaikech/2b9d86a7db01f72e88090116cb5fee1f to your computer and use it in GitHub Desktop.
Workaround: createdDate cannot be used with searchFiles of DriveApp in Google Apps Script

Workaround: createdDate cannot be used with searchFiles of DriveApp in Google Apps Script

Unfortunately, in the current stage, in order to retrieve the file list using the created date, the search query of createdDate cannot be used with searchFiles method of DriveApp in Google Apps Script. This has already been reported at this issue tracker In this post, I would like to introduce a workaround for searching the files using the created date.

Issue and workaround

  • The parameter of "searchFiles" method of DriveApp uses the search query for Drive API v2. When I tested createdDate > '####-##-##' for "searchFiles" and "Files: list" of Drive API v2, I confirmed errors like Invalid argument: q and Invalid query occurred, respectively.

  • Fortunately, when Drive API v3 is used, createdTime can be used. createdTime of Drive API v3 is the same with createdDate of Drive API v2.

In this post, as a workaround, I would like to introduce a sample script using Drive API v3 instead of Drive API v2 ("searchFiles" of DriveApp).

Sample script

This script uses Drive API. So, please enable Drive API at Advanced Google services.

function myFunction() {
  const after = 1; // This is a sample. The file list of the files created after 1 day is retrieved.

  let fileList = [];
  const query = `createdTime > '${Utilities.formatDate(
    new Date(new Date().getTime() - 3600 * 1000 * 24 * after),
    "GMT",
    "yyyy-MM-dd"
  )}' and trashed=false`;
  let pageToken = "";
  do {
    const url = encodeURI(
      `https://www.googleapis.com/drive/v3/files?q=${query}&pageSize=1000&pageToken=${pageToken}&fields=files(id,name,createdTime),nextPageToken&orderBy=createdTime`
    );
    const res = UrlFetchApp.fetch(url, {
      headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() },
    });
    const obj = JSON.parse(res.getContentText());
    if (obj.files.length > 0) {
      fileList = [...fileList, ...obj.files];
    }
    pageToken = obj.nextPageToken;
  } while (pageToken);
  console.log(fileList);
}
  • When this script is run, from your Google Drive, the file list of the files created after 1 day is retrieved.

References

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