我的代码类似于文件搜索引擎,它接受你正在寻找的关键字,对用户google驱动器中的所有文件进行全文搜索,并通过在电子表格中显示返回文件名、url源和文件夹。代码:
function search(Phrase, FolderID) {
// Prompt the user for a search term
var searchTerm = Browser.inputBox("Enter the string to search for:");
// Get the active spreadsheet and the active sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
// Set up the spreadsheet to display the results
var headers = [["File Name", "Folder", "URL"]];
sheet.clear();
sheet.getRange("A4:C4").setValues(headers);
// Search the files in the user's Google Drive for the search term based on if the word is included in thefile or name
// Search Reference Guide: https://developers.google.com/apps-script/reference/drive/drive-app#searchFiles(String)
var files = DriveApp.searchFiles("fullText contains '"+searchTerm.replace("'","\'")+"'");
//var SearchString = 'fullText contains "' + Phrase + '" and "' + FolderID + '" in parents';
//var files = DriveApp.searchFiles(SearchString);
// create an array to store our data to be written to the sheet
var output = [];
// Loop through the results and get the file name, URL, and Folder
while (files.hasNext()) {
var file = files.next();
var name = file.getName();
//var type = file.getMimeType(); //File type
var url = file.getUrl();
var folderNames = "";
var folders = file.getParents();
while (folders.hasNext()) {
var folder = folders.next();
//Logger.log(folder.getName());
folderNames += folder.getName() + ", ";
}
// push the file details to our output array (essentially pushing a row of data)
output.push([name, folderNames, url]);
}
// write data to the sheet
sheet.getRange(5, 1, output.length, 3).setValues(output);
}
我绝对是编码/谷歌脚本的初学者,所以我想要一些建议(如果有的话)来帮助减少代码完成一次运行并获得结果所需的时间,因为目前我必须等待5-15秒才能得到结果。
发布于 2018-05-31 07:45:41
使用Drive API怎么样?虽然我不确定这个建议对你的情况是否有用,但你能试试这个脚本吗?修改后的脚本如下。当您使用此脚本时,请在高级Google服务和API控制台启用Drive API。
在高级谷歌服务中启用驱动器应用编程接口v2
Enable Drive API at API console
<代码>H122在搜索API和服务时,输入“驱动器”。点击驱动接口。
修改后的脚本:
function search(Phrase, FolderID) {
// Prompt the user for a search term
var searchTerm = Browser.inputBox("Enter the string to search for:");
// Get the active spreadsheet and the active sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
sheet.clear();
// Below script was added.
var optionalArgs = {
q: "fullText contains '"+searchTerm.replace("'","\'")+"'",
fields: "items(alternateLink,parents/id,title)"
};
var files = Drive.Files.list(optionalArgs).items; // Retrieve files by search text.
var res = files.map(function(e){return [e.title, e.parents.map(function(f){return DriveApp.getFolderById(f.id).getName()}).join(", ") , e.alternateLink]});
var values = [["File Name", "Folder", "URL"]];
Array.prototype.push.apply(values, res);
sheet.getRange(4, 1, values.length, 3).setValues(values);
}
参考文献:
如果这对你的情况没有帮助,我很抱歉。
https://stackoverflow.com/questions/50611185
复制相似问题