如何使用谷歌脚本获取驱动器中文件夹的文件夹ID?

时间:2018-03-14 15:58:40

标签: google-apps-script google-drive-api

对于我正在处理的项目,我创建了一个触发器,用于在每年年初运行我的makeCopy()函数。目标是制作电子表格的副本并将其保存在我的驱动器中已创建的文件夹中。在这个函数中,我还为新的一年创建了一个新文件夹。

function makeCopy(){

  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var d = new Date();
  var year = d.getYear();
  var FolderName = "Time Off Request - " + year;

  DriveApp.createFolder(FolderName);

  year = year - 1;
  var FileName = "Copy of Time Off Request - " + year; 
  Logger.log(FolderName);
  FolderName = "Time Off Request - " + year;
  var FolderID = DriveApp.getFoldersByName(FolderName).next().getId();
  Logger.log(FolderID);

  var destFolder = DriveApp.getFolderById(FolderID);
  Logger.log(destFolder);


  DriveApp.getFileById(sheet.getId()).makeCopy(FileName, destFolder);

}

此代码实际上是第一次运行和工作。但是,每次我尝试再次测试时,我都会收到错误,"无法检索下一个对象:迭代器已经到了结尾。 "在我试图获取我的文件夹ID的行。如何修复此错误并获取驱动器中文件夹的文件夹ID,以便我可以将电子表格复制到该文件夹​​。

2 个答案:

答案 0 :(得分:0)

您收到特定错误Cannot retrieve the next object: iterator has reached the end.,因为搜索该文件夹名称会产生一个空结果集。 如果您将程序结构更改为仅使用next(),如果迭代器的hasNext()方法返回true,则不会再出现该错误。但是,这样的更改不会使您的搜索词突然找到结果。但是,它允许使用不同的搜索查询重复尝试。

我建议将变量重命名为表达其意图:

// Copy the current file into last year's folder, and create this year's folder.
function makeCopy() {
  var now = new Date();
  var thisYear = now.getYear();
  var lastYear = thisYear - 1;

  var query = "Time Off Request - " + lastYear;
  var folderIterator = DriveApp.getFoldersByName(query);
  // Instead of throwing an error, you could modify this to be a while loop
  // that requests a search term from the user - see Browser/UI and inputBox
  // and updates folderIterator. If you do that, you'll want to add guards
  // that ensure the correct folder will be the first result.
  if (!folderIterator.hasNext()) {
    throw new Error("Bad search term - no folders with name '" + query + "' exist!");
  }

  var lastYearFolder = folderIterator.next();
  console.log({message: "Backup of Time Off Requests",
               query: query,
               destFolder: lastYearFolder.getName()}
  ); // View->Stackdriver Logging

  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var backupName = "Copy of Time Off Request - " + lastYear; 
  DriveApp.getFileById(sheet.getId()).makeCopy(backupName, lastYearFolder);

  // Before exiting, now that the backup is done, create this year's folder.
  DriveApp.createFolder("Time Off Request - " + thisYear);
}

答案 1 :(得分:0)

createFolder返回一个Folder对象,但代码并没有提出这个问题。而不是

DriveApp.createFolder(FolderName);

使用

var myFolder =  DriveApp.createFolder(FolderName);

然后使用getId

获取文件夹ID
var FolderID = myFolder.getId();