Skip to content

Instantly share code, notes, and snippets.

@rluvaton
Last active June 26, 2023 12:15
Show Gist options
  • Save rluvaton/0e0ba97c94180d1c88d42258bf187890 to your computer and use it in GitHub Desktop.
Save rluvaton/0e0ba97c94180d1c88d42258bf187890 to your computer and use it in GitHub Desktop.
Get Folder Size - App Script
var count = 0;
function myFunction() {
Logger.log('Starting');
// Please Write the path of the folder you want sub path seperated with slash(,) (spaces are counted)
// for example: for myFolder/test -> myFolder,test
// And NOT myFolder, test
var folders = [];
if(!folders) {
return;
}
Logger.log('Finished: ' + formatSize(getFolderSize(findFolder(null, folders, 0))));
Logger.log('Count: ' + count);
}
// a - bytes
// b - number after point
function formatSize(a, b) {
if(0==a)return"0 Bytes";var c=1024,d=b||2,e=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],f=Math.floor(Math.log(a)/Math.log(c));return parseFloat((a/Math.pow(c,f)).toFixed(d))+" "+e[f]
}
function findFolder(parent, folderNames, i) {
if(folderNames.length - 1 < i) {
return parent;
}
var folderName = folderNames[i];
Logger.log(folderName);
if(!parent) {
var folders = DriveApp.searchFolders('title contains "'+folderName+'"');
parent = folders.next();
}
var foundedFolders = parent.getFolders();
while (foundedFolders.hasNext()){
var folder = foundedFolders.next();
return findFolder(folder, folderNames, i + 1);
}
}
function getFolderSize(folder) {
if(!folder) {
return 0;
}
var size = 0;
var files = folder.getFiles();
while (files.hasNext()){
var file = files.next();
count++;
size +=file.getSize();
}
var subFolders = folder.getFolders();
while (subFolders.hasNext()){
var subFolder = subFolders.next();
size += getFolderSize(subFolder);
}
return size;
}
@saifujiwara
Copy link

Is this code still works? Because I tried and I got error. I have folder for example My Drive/Chess. but I got error: Exception: Cannot retrieve the next object: iterator has reached the end
Capture

And this is my Google Drive folder structure
image

Please help me, thank you.

@rluvaton
Copy link
Author

rluvaton commented Jun 1, 2021

Is this code still works?

I'm updating the code now mate

@rluvaton
Copy link
Author

rluvaton commented Jun 1, 2021

@saifujiwara does it work now?

@saifujiwara
Copy link

@rluvation It still doesn't work, stil got the same error. Sorry, but with my folder structure My Drive/Chess, how suppose I write it in the code? Is it My Drive,Chess or "My Drive","Chess" or what? Because I'm not good in programming. Thanks.

@saifujiwara
Copy link

image

This is the error that I got.

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