Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created February 24, 2023 05:36
Show Gist options
  • Save tanaikech/bbf37f05f5f5a98d346295f6e4aa3c48 to your computer and use it in GitHub Desktop.
Save tanaikech/bbf37f05f5f5a98d346295f6e4aa3c48 to your computer and use it in GitHub Desktop.
Retrieving Total File Sizes in Specific Folder of Google Drive using Google Apps Script

Retrieving Total File Sizes in Specific Folder of Google Drive using Google Apps Script

This is a sample script for retrieving the total file sizes in the specific folder of Google Drive using Google Apps Script.

There is a case where you want to retrieve the total file sizes in the specific folder of Google Drive using Google Apps Script. In this post, I would like to introduce a sample script for achieving this.

Sample script

Before you use this script, please enable Drive API at Advanced Google services. And please install FilesApp of a Google Apps Script library.

function myFunction() {
  const folderId = "###"; // Please set your folder ID.
  const res = FilesApp.createTree(folderId, null, "files(size)").files.reduce(
    (o, { filesInFolder }) => {
      filesInFolder.forEach(({ size }) => {
        if (size) {
          o.totalSize += Number(size);
          o.filesWithSize++;
        } else {
          o.filesWithoutSize++;
        }
      });
      return o;
    },
    { filesWithSize: 0, filesWithoutSize: 0, totalSize: 0 }
  );
  console.log(res);
}
  • In this script, all files in the subfolders under the specific folder folderId are searched.

Testing

When this script is run, the following result is obtained.

{
  "filesWithSize": 100,
  "filesWithoutSize": 5,
  "totalSize": 123456789
}
  • filesWithSize: Number of files with the file size.

  • filesWithoutSize: Number of files without the file size.

    • The official document says about size as follows. Ref

      size: The size of the file's content in bytes. This field is populated for files with binary content stored in Google Drive and for Docs Editors files; it is not populated for shortcuts or folders.

  • totalSize: Total size. The unit is bytes.

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