【问题标题】:How to search and get a specific file using Google Apps Script to search in the Parent folder and in its subfolders?如何使用 Google Apps 脚本在父文件夹及其子文件夹中搜索并获取特定文件?
【发布时间】:2021-09-15 22:25:42
【问题描述】:

我目前面临的问题是:

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

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

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

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

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

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

谢谢!

附言。子文件夹的数量可能比 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)],
      });
    }
}

【问题讨论】:

    标签: google-apps-script google-sheets directory subdirectory


    【解决方案1】:

    一种选择是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;
    }
    

    这将返回一个数组,其中包含您指定的子文件夹中具有该名称的所有 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

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

    【讨论】:

    猜你喜欢
    • 2013-06-06
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多