获取 Google 驱动器文件夹中的最新文件

Get the Newest File in a Google Drive Folder

我的 Google 应用程序脚本中有以下几行,但文件 API 现已弃用,我无法更新代码。

原文为:

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);`

我需要我的脚本转到我的驱动器上的文件夹,在该文件夹中获取最新的 google 电子表格文件并打开它。

不用担心,您可以改用 DriveApp。请参阅此页面,了解您可以对云端硬盘文件使用的所有可能方法:https://developers.google.com/apps-script/reference/drive/drive-app

希望对您有所帮助!

这是获取文件夹中最新文件的代码:

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()) {//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 do
      return;
    }

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