如何使用 Google Apps 脚本在父文件夹及其子文件夹中搜索并获取特定文件?

How to search and get a specific file using Google Apps Script to search in the Parent folder and in its subfolders?

我目前面临的问题是:

我创建了一个名为“Parent”的主文件夹,文件夹 ID 为:eg abcde12345.

在父文件夹中,有 3 个 diff 文件夹(例如文件夹 A、文件夹 B、文件夹 C)和它们自己的文件。

我要找的具体文件是:“要sent.pdf的文件”

这个文件,比如我放在C文件夹里

然而,我在下面写的脚本(删除了一些细节)只搜索父文件夹中的特定文件。搜索不会进入文件夹 A、B 或 C 以查找具有确切文件名的文件。

有没有办法在 Parent + A + B + C 中搜索此特定文件,而无需在脚本中对文件夹 A、B、C ID 进行硬编码?

谢谢!

Ps。子文件夹的数量可能会比A、B、C增长更多,在这些子文件夹中,我正在考虑创建更多层。

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)],
      });
    }
}

一种选择是 recursively 在目标文件夹及其子文件夹中搜索文件:

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;
}

这将 return 一个数组,其中包含您指定的子文件夹中具有该名称的所有 files

相关:

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

Google apps script - iterate folder and subfolder