Google-apps-script – Google Scripts DriveApp searchFiles does not work on a specific folder

google-apps-scriptgoogle-drive-search

I am trying to search through some files stored in a specific folder on Google Drive using Google Scripts. This is for creating a "Deployment Folder" for my school for the upcoming academic session.

Code below:

function start() {
    SearchFiles("TextToSearchFor");
}

function SearchFiles(query) {

  //put the source content folder ID and destination Drive folder ID here
  srcContentFolderID="srcID";

  try{  
    var files = DriveApp.getFolderById(srcContentFolderID).searchFiles('(title contains "' + query + '")');
    while (files.hasNext()) {
      var file = files.next();
      var fileName = file.getName();
      var parents = file.getParents();
      while (parents.hasNext()) {
        var parent = parents.next();
        if(parent.getId() == srcContentFolderID){
          //found the correct source of the file. Log it.
          Logger.log("Parent name: " + parent.getName() + " File name:" + fileName);
        }
        else
          Logger.log("NOT FOUND: " + parent.getName() + " File name:" + fileName);
      }
    }
  } catch(e){
    Logger.log("ERROR: "+e.Message);
  }

I am using Apps Script runtime powered by Chrome V8.

I have the following question:

DriveApp.getFolderById(srcContentFolderID).searchFiles('(title contains "' + query + '")') doesn't work. I get the following exception:

Exception: Invalid argument: q at SearchFiles at Array.forEach GS_INTERNAL_top_function_call.gs

Only searching using DriveApp.searchFiles('(title contains "' + query + '")') does work, but it gives a lot of results.
I am trying to do this for hundreds of files, so I risk timing out if I have to sift through multiple search results for every query.

I have looked through StackExchange for quite some time to figure out why an exception is generated, to no avail. Appreciate any help on this!

Note: I have seen the following links:

https://stackoverflow.com/questions/35661979/searching-for-file-by-name-within-a-folder-in-google-drive-using-google-scripts

https://stackoverflow.com/questions/52100052/folder-searchfiles-method-raises-invalid-argument-q-error/52100980

https://developers.google.com/drive/api/v2/ref-search-terms

https://stackoverflow.com/questions/56596130/google-app-script-driveapp-getparents-not-working-as-expected

Best Answer

The code works fine for me on a simple test. I suggest you to add more log statements but instead of using Logger use console. i.e. You could log every file name and their Mime Type in order to find if there is an specific file that is causing the error.

Also beside logging only e.message include the e.stack

console.error('%s, %s', e.message, e.stack)

NOTE: e.Message is wrong, it should be e.message