Google-sheets – How to list total files for every subfolder in Google Drive

google sheetsgoogle-apps-scriptgoogle-drive

On google drive I have a directory with over 1000 subfolders. I want to list all subfolders with the total amount of files for each subfolder. This is the script I got so far but it doesn't work cause it's just listing 0 for all subfolders

// replace your-folder below with the root folder for which you want a listing
function listFolderContents() {
  var foldername = 'CC-Part2';
  var folderlisting = 'listing of folder ' + foldername;

  var folders = DriveApp.getFoldersByName(foldername)
  var folder = folders.next();
  var contents = folder.getFolders();

  var ss = SpreadsheetApp.create(folderlisting);
  var sheet = ss.getActiveSheet();
  sheet.appendRow( ['name', 'size'] );

  var subfolder;
  var name;
  var size;
  var row;
  while(contents.hasNext()) {
    subfolder = contents.next();
    name = subfolder.getName();
    size = subfolder.getSize();
    sheet.appendRow( [name, size] );     
  }  
};

Can anyone help me fix this script?

Best Answer

You can find a script on labnol.org which is like the 'tree' command in DOS but for Google Drive.

To get started, click here and authorize the script to access the files in your Google Drive. Once the authorization is complete, it may take a minute to generate the entire Google Drive tree. You’ll then get a link to download an HTML file that mirrors your Drive structure. You can directly send the file to the printer as well.