问题: - 我需要从某些Google云端硬盘文件夹中获取最新创建文档的名称和ID。
解决方案: - 我无法找到一个简单的方法来获取它,因此,为文件夹中的文件创建了一个循环以获取最大日期 - 然后再次在文件夹中循环以匹配日期并记录名称和日期 - 下面的代码(当如上所述评论)适用于解决方案。
我没有使用不同的文件夹名称重写整个代码,而是尝试为文件夹名称创建一个循环。
然而,应用程序脚本进入无限循环,给出最大执行时间限制消息。 任何帮助表示赞赏。
function Get_lastestdate() {
//Define Spreadsheet and sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("PEOPLE");
//comment from here to work properly
for (var i =1; i < 4; i++) {
if (i = 1) { var foldername = "Folder1"}
if (i = 2) { var foldername = "Folder2"}
if (i = 3) { var foldername = "Folder3"}
// till here
//Define folder and files
var folder = DocsList.getFolder(foldername); //set folder name in case commenting.
var lastfile = folder.getFiles();
//Make a blank array
var noofdaysarray = []
var yeararray = []
//Loop to get all No of days in a year & the year
for (var i in lastfile) {
noofdaysarray.push(Utilities.formatDate(lastfile[i].getDateCreated(),"GMT","D"));
yeararray.push(Utilities.formatDate(lastfile[i].getDateCreated(),"GMT","y"));
}
//Get the max date from date and year
var largestdate = Math.max.apply(Math, noofdaysarray);
var largestyear = Math.max.apply(Math, yeararray);
//Get maximum available date
var matchcriteria = largestdate + largestyear
//Again loop for matching criteria with the actual date uploaded
for (var i in lastfile) {
var lastdate = Utilities.formatDate(lastfile[i].getDateCreated(),"GMT","D");
var lastyear = Utilities.formatDate(lastfile[i].getDateCreated(),"GMT","y");
var wholedate = parseInt(lastdate) + parseInt(lastyear); //parseInt is for converting text to number
//Get doc name if both dates matches
if (wholedate == matchcriteria) {
Logger.log(lastfile[i].getId());
Logger.log(lastfile[i].getName());
}
}
} //comment this as a part of loop
}
之间: - 如果有更简单的方法,请告诉我。
答案 0 :(得分:1)
不要在内圈和外圈中使用“i”。这将是一个问题。
做这样的事情会不会更容易,所以你只做一个循环?
var mostRecentDate = new Date(2000,01,01);
var fileName="";
var fileId="";
for(var i = 1; i<5; i++){
var folder = DocsList.getFolder('Folder'+i);
var files = folder.getFiles();
for(var j in files) {
if(files[j].getDateCreated()>mostRecentDate){ //or getLastUpdated
mostRecentDate=files[j].getDateCreated();
fileName=files[j].getName();
fileId=files[j].getId();
}
}
}
Logger.log("File: " + filename + " Id: " + fileId + " Created: " + mostRecentDate);
如果你有大量的文件,你可能需要进行分页。要迭代的文件夹。
答案 1 :(得分:1)
您可以使用DocsList检索上次修改的文件。你告诉过你想要最后一次创建,但也许最后一次修改可能是有用的。检查下面的代码:
function findLastModified() {
//Retrieve folder
var folder = DocsList.getFolderById("0B0kQD4hSd4KASUJKb2cya0NET1U");
//Ask for 5 files
var numberOfFiles = 5;
//The first parameter is the search query, in this case we want all files
var filesResult = folder.findForPaging("", 5);
//By Default they will be sorted by last modified date
var files = filesResult.getFiles();
Logger.log("Found "+files.length+" files");
//Iterate
for(var x in files) {
var file = files[x];
Logger.log(file.getLastUpdated());
}
}
实时版here。