0
votes

The issue I'm current facing is:

I created a main folder named "Parent" with the folder ID:eg abcde12345.

Within the Parent folder, there are 3 diff folders (eg. Folder A, Folder B, Folder C) with their own files.

The specific file I am looking for is: "File to be sent.pdf"

This file, I placed in Folder C for example.

However, the script I wrote below (with some details edited out) only search for the specific file in the Parent folder. The search does not go into Folder A,B or C to look for the file with the exact filename.

Is there a way to search for this specific file within the Parent + A + B + C without hardcode the Folder A,B,C IDs in the script?

Thank you!

Ps. The number of sub folders may grow more than A,B,C and in these sub folders, I am thinking of creating more layers.

function ReturnWork(){
 
var markedFolder = DriveApp.getFolderById("abcde12345");
 
var ws = SpreadsheetApp.getActiveSpreadsheet();
 
/*This section which I edited out to shorten this post contains variables example:
-emailAddress
-subject
-etc... all details needed for the mailApp below.*/
 
 
var docName = 'File to be sent.pdf';
var markedFiles = markedFolder.getFilesByName(docName);


      if(markedFiles.hasNext()){
      MailApp.sendEmail({
      to: emailAddress,
      subject: subjectMarked,
      replyTo: centre_email,
      htmlBody : markedHTML.evaluate().getContent(),
      attachments: [markedFiles.next().getAs(MimeType.PDF)],
      });
    }
}
1

1 Answers

1
votes

One option would be to recursively search the file in the target folder and its subfolders:

function searchFileTest() {
  const targetFolderId = 'abc123';
  const fileName = 'File to be sent.pdf';
  const filesFound = searchFile(fileName, targetFolderId);
  for (const file of filesFound) {
    Logger.log('File found: ' + file.getUrl());
  }
}

function searchFile(fileName, folderId) {
  let files = [];

  // Look for file in current folder
  const folderFiles = DriveApp.getFolderById(folderId).getFiles();
  while (folderFiles.hasNext()) {
    const folderFile = folderFiles.next(); 
    if (folderFile.getName() === fileName) {
      files.push(folderFile);
    }
  }

  // Recursively look for file in subfolders
  const subfolders = DriveApp.getFolderById(folderId).getFolders(); 
  while (subfolders.hasNext()) {
    files = files.concat(searchFile(fileName, subfolders.next().getId()));
  }

  return files;
}

This will return an array with all the files that have that name in the folder you specify of its subfolders.

Related:

How to search contents of files in all folders and subfolders of google drive in Apps Scripts?

Google apps script - iterate folder and subfolder

assign hyperlink to cell in google sheets to google drive files using google app script