Skip to content Skip to sidebar Skip to footer

Get The Newest File In A Google Drive Folder

I have the following lines in my Google App script, but the File API is now deprecated and I am unable to update the code. The original lines are: var folder = DocsList.getFolder('

Solution 1:

Here is the code that will get the newest file in the folder:

functiongetNewestFileInFolder() {
  var arryFileDates,file,fileDate,files,folder,folders,
      newestDate,newestFileID,objFilesByDate;

  folders = DriveApp.getFoldersByName('yourFolderName');  
  arryFileDates = [];
  objFilesByDate = {};

  while (folders.hasNext()) {
    folder = folders.next();

    files = folder.getFilesByType("application/vnd.google-apps.spreadsheet");
    fileDate = "";

    while (files.hasNext()) {//If no files are found then this won't loop
      file = files.next();
      Logger.log('xxxx: file data: ' + file.getLastUpdated());
      Logger.log('xxxx: file name: ' + file.getName());
      Logger.log('xxxx: mime type: ' + file.getMimeType())
      Logger.log(" ");

      fileDate = file.getLastUpdated();
      objFilesByDate[fileDate] = file.getId(); //Create an object of file names by file ID

      arryFileDates.push(file.getLastUpdated());
    }

    if (arryFileDates.length === 0) {//The length is zero so there is nothing//to doreturn;
    }

    arryFileDates.sort(function(a,b){return b-a});

    Logger.log(arryFileDates);

    newestDate = arryFileDates[0];
    Logger.log('Newest date is: ' + newestDate);

    newestFileID = objFilesByDate[newestDate];

    Logger.log('newestFile: ' + newestFileID);
    //return newestFile;var ss = SpreadsheetApp.openById(newestFileID);
    Logger.log('file name that is now open: ' + ss.getName());
  };
};

Solution 2:

No worries about that, you can use DriveApp instead. Refer to this page for all the possible methods you can use on Drive files: https://developers.google.com/apps-script/reference/drive/drive-app

Hope that helps!

Post a Comment for "Get The Newest File In A Google Drive Folder"