Home > front end >  Apps Script: folder.getFiles is not a function error in Trigger
Apps Script: folder.getFiles is not a function error in Trigger

Time:03-12

Good day. I have problem in Google Apps Script. When I run my function in apps script its working fine but when I add it in a trigger this error always occurs in first run.

TypeError: folder.getFiles is not a function

This is the code. I use this code to get all files in all folders and subfolders.

var level=0;
function getFnF(folder) {
  var folder= folder || DriveApp.getFolderById('root folder ID');
  var ss=SpreadsheetApp.openById('google sheet ID');
  var sh=ss.getSheetByName('List');
   

  var files=folder.getFiles();
  while(files.hasNext()) {
    var file=files.next();
    var fileid = file.getId();
    var TimeStamp =   Utilities.formatDate(new Date(), "GMT 8", "MMMM dd, yyyy HH:mm:ss")
    var filesize = file.getSize()/ 1024 / 1024;
    var lastrow = sh.getLastRow();
    var filename =file.getName();

    sh.appendRow([TimeStamp,lastrow,filename,file.getName(),filesize.toFixed(2),fileid);
    Logger.log('Item added in list: ['  lastrow "] "   filename);
  }
  var subfolders=folder.getFolders() 
  while(subfolders.hasNext()) {
    var subfolder=subfolders.next();
    //subfolders only
    level  ;
    getFnF(subfolder);
  }
  level--;
}

I hope you can help me.

CodePudding user response:

From When I run my function in apps script its working fine but when I add it in a trigger this error always occurs in first run., I'm not sure about the kind of trigger. But when the function is run by a trigger, the event object is given to the 1st argument. So, in this case, how about the following modification?

Modified script:

var level = 0;
function getFnF(e, folder = DriveApp.getFolderById('root folder ID')) {
  var ss = SpreadsheetApp.openById('google sheet ID');
  var sh = ss.getSheetByName('Sheet1');
  var files = folder.getFiles();
  while (files.hasNext()) {
    var file = files.next();
    var fileid = file.getId();
    var TimeStamp = Utilities.formatDate(new Date(), "GMT 8", "MMMM dd, yyyy HH:mm:ss")
    var filesize = file.getSize() / 1024 / 1024;
    var lastrow = sh.getLastRow();
    var filename = file.getName();
    sh.appendRow([TimeStamp, lastrow, filename, file.getName(), filesize.toFixed(2), fileid]);
    Logger.log('Item added in list: ['   lastrow   "] "   filename);
  }
  var subfolders = folder.getFolders()
  while (subfolders.hasNext()) {
    var subfolder = subfolders.next();
    //subfolders only
    level  ;
    getFnF(e, subfolder);
  }
  level--;
}
  • By this modification, when the function getFnF by a trigger, the function is run as the initial value of folder of DriveApp.getFolderById('root folder ID').

  • By the way, when you want to run this function from another function instead of the trigger, please call this as getFnF("dummy", folder).

  • Related