0
votes

I have a folder in Google drive in to which files are regularly dumped from a reporting tool. The files are in .xls format. They all have the same name and I want to identify the most recent file so that I can import the data in to a Google sheet.

As you will be able to tell from the below I am new to Google Apps script. I have been trying to catch the various files from the file iterator into an array to run a Math.max function on the result to end up with just one value. Of course, once I have identified the newest date I also need to return the fileID associated with - but I haven't got that far yet. I am probably heading in the completely wrong direction so any tips/guidance would be greatly appreciated.

function listLatestFile(id) {
var folder = DriveApp.getFoldersByName("GmailAttachments");
var files = DriveApp.getFilesByName('mrp_out.xlsx');
while (files.hasNext()) {
 var file = files.next();
 var date = (1 - file.getDateCreated());
 var datediff = new Array(date);
 var datelast = Math.max(datediff);
 Logger.log(datelast);
 } 
//Logger.log(date);
};
2

2 Answers

2
votes

You were not very far from the solution... I tried using a slightly different approach : I store all dates and IDs in an 2D array, I sort the array and retrieve the first element (after sorting) in the 2cond dimension to return the file ID.

code :

function listLatestFile() {
  var folder = DriveApp.getFoldersByName("GmailAttachments");
  var files = DriveApp.getFilesByName('mrp_out.xlsx');
  var result = [];
  while (files.hasNext()) {
    var file = files.next();
    result.push([file.getDateCreated(),file.getId()]);
 } 
  Logger.log(result);
  var id = result.sort()[0][1];
  Logger.log(id);
  return id;// return most recent file ID
};

EDIT : if you want to have more control on the sorting method, you can use a more "sophisticated" sort method like below :

   ...// same as above
  result.sort(function(x,y){
    var xp = x[0];// get first element in inner array
    var yp = y[0];
    return xp == yp ? 0 : xp < yp ? -1 : 1;// choose the sort order
  });    
  var id = result[0][1];
  Logger.log(id);
  return id;
};
0
votes

The answer posted above didn't work for me, so I came up with my own solution, which works.

Obviously (in late 2017) google drive sorts the files. So the last created file is the first in the iterator.

Here's the code to get the latest file ID :

 function getLatestFileId(){

   var folder = DriveApp.getFoldersByName("Aff Comm");
   var files = folder.next().getFiles();
   var lastFileId = files.next().getId();


   return lastFileId.toString();

}