Get the Newest File in a Google Drive Folder

痴心易碎 提交于 2019-12-24 04:49:09

问题


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('Folder Name');
var file = folder.getFilesByType(DocsList.FileType.SPREADSHEET)[0];
var filename = file.getName(); //and get its name
var fileId = file.getId(); // its ID
var fileurl = file.getUrl(); //and its url
var source = SpreadsheetApp.openById(fileId);`

I need my script to go to a folder on my drive, get the LATEST google spreadsheet file in this folder and open it.


回答1:


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

function getNewestFileInFolder() {
  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()) {
      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());
    }
    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());
  };
};



回答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!



来源:https://stackoverflow.com/questions/28323703/get-the-newest-file-in-a-google-drive-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!