Home > other >  How to search for a file in subfolders inside subfolders using apps script?
How to search for a file in subfolders inside subfolders using apps script?

Time:05-23

I'm trying to find a file which may be in a subfolder, but it could also be inside a subfolder of a subfolder. I've followed this answer's approach, but still...

When I place the file inside the 'second subfolder, the script is not finding it.

function updateClientWb() {
  var clientId = 'AA001'
  var parent_folderID = 'folderidsafafdasadasda2D-U';

  var parent_folder = DriveApp.getFolderById(parent_folderID);
  var subFolders = parent_folder.getFolders();
  var searchForClientId = "title contains '"   clientId   "'";
  var clientSeoProjectWb = [];

  while (subFolders.hasNext()) {
    var thisSubFolder = subFolders.next();//THIS IS PROBABLY WHERE THE FLAW IS
    var clientFiles = thisSubFolder.searchFiles(searchForClientId);
    while (clientFiles.hasNext()) {
      var files = clientFiles.next();
      if (files.getName().indexOf('File Name Part') > -1) {
        clientSeoProjectWb.push(files.getId());
      }
    }
  }
  return;
}

Appreciate your help

CodePudding user response:

Try something like this. Note that the clientSeoProjectWB is defined in the script file, not a function so both functions can interact with it. I didn't test it, but I think this would put you on the proper track. Make sure your first folder is identified in the startSearch function.

//need to have shared array
var clientSeoProjectWb =[];

function startSearch(){
  searchFolder_(DriveApp.getFolderById('???topFolderID'))
  //Final array with all files...
  clientSeoProjectWb.forEach(x => Logger.log(x));
}

function searchaFolder_(_aFolder) {
  var someFiles = _aFolder.getFiles();

  while(someFiles.hasNext()){
    var aFile = someFiles.next();
    if(aFile.getName().indexOf('File Name Part') > -1){
      //Found file add to array
      clientSeoProjectWb.push(aFile.getId());
    }
  }
  var someFolders = _aFolder.getFolders();
    while(someFolders.hasNext()){
    var newFolder = someFolders.next();
    //launch function again with new folder
    searchaFolder_(newFolder);
  }
}
  • Related