使用谷歌脚本在Google云端硬盘中的文件夹中按名称搜索文件

s_l*_*_ll 4 google-apps-script google-drive-api

在Google云端硬盘中,我正在尝试在当前目录中搜索文件.该脚本链接到电子表格,因此它找到电子表格的父目录,然后使用其id在文件夹中为名为Title的文件指定搜索.

我到目前为止的代码是:

function searchFolder(){

//get current folder id
var ss = SpreadsheetApp.getActive(); //current spreadsheet
var directParents = DriveApp.getFileById(ss.getId()).getParents();

while( directParents.hasNext() ) {
  var folder = directParents.next();
  var folderId = folder.getId();
  Logger.log(folder.getName() + " has id " + folderId);
}

//get files in folder
var parent = DriveApp.getFolderById(folderId); // folder Id
var search = 'name contains "Title"';
var specificFolder = parent.searchFiles(search);

while (specificFolder.hasNext()) {
  var file = specificFolder.next();
  Logger.log(file.getName());
  Logger.log(file.getId());
}
}
Run Code Online (Sandbox Code Playgroud)

我在while循环的开头得到错误"Invalid argument:query",这表明没有找到任何文件.

这个错误似乎只发生在我按名称搜索时.如果我将搜索变量更改为'fullText包含'hello"'(文件标题中包含'hello'),则没有问题.如何通过名称进行搜索?

要复制错误,请在Google驱动器上的文件夹中制作两个电子表格.一个电子表格将脚本链接到它,另一个电子表格被命名为"标题"并正在搜索.谢谢.

Br.*_*yan 7

正如Srikanth指出的那样,事实title contains并非如此name contains.代码可以更简单,请尝试以下代码.您不需要使用spreadhseet,只需使用简单的Google Apps脚本项目文件即可.右键单击Drive---> More--->的空白区域Google Apps Script

function SearchFiles() {
  //Please enter your search term in the place of Letter
  var searchFor ='title contains "Letter"';
  var names =[];
  var fileIds=[];
  var files = DriveApp.searchFiles(searchFor);
  while (files.hasNext()) {
    var file = files.next();
    var fileId = file.getId();// To get FileId of the file
    fileIds.push(fileId);
    var name = file.getName();
    names.push(name);

  }

  for (var i=0;i<names.length;i++){
    Logger.log(names[i]);
    Logger.log("https://drive.google.com/uc?export=download&id=" + fileIds[i]);

  }

}
Run Code Online (Sandbox Code Playgroud)

另请查看以下链接:

1)搜索文件夹中的所有文档 2)搜索驱动器文件