Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google-apps-script count files in folder

I've had a search but cannot seem to find what I am looking for.

I am seeking the code to enable me to do this pseudocode:

  1. Count number of files in specific Google Drive folder (by folder Id)
  2. If file count is above 'x' do this {other piece of code}
  3. else, exit

Can anyone help me out?

like image 234
witham Avatar asked Feb 10 '23 02:02

witham


1 Answers

I can't find any method to give the count for the number of files, so I guess you'll need to loop through every file, and have a counter:

function countFilesInFolder() {
  var count,file,files,theFolder;//Define variables without assigning a value

  theFolder = DriveApp.getFolderById('your file ID');
  files = theFolder.getFiles();

  count = 0;

  while (files.hasNext()) {
   count++;
   file = files.next();
   //Logger.log(file.getName());
   if (count > 5) {
     fncNextFunction();
     break;
   };
 };

  Logger.log(count);
};

function fncNextFunction() {
  Logger.log('fncNextFunction');

};

Note: If I just have the counter increment without getting the next file, the script editor freezes.

Here is an alternative method using the advanced Drive Service:

//This requires the Drive API To be turned on in the Advanced Google Services
function countFilesInFolder() {

 var query = 'trashed = false and ' +
        "'Your Folder ID here' in parents";

  var filesInFolder = Drive.Files.list({q: query});

  Logger.log('filesInFolder: ' + filesInFolder.items.length);

  for (var i=0;i<filesInFolder.items.length;i++) {
    //Logger.log('key: ' + key);
    var thisItem = filesInFolder.items[i];
    Logger.log('value: ' + thisItem.title);
  };
};

For an example of using page tokens to list more than 100 results, see The Documentation

like image 110
Alan Wells Avatar answered Mar 05 '23 12:03

Alan Wells