在云端硬盘中选择特定文件夹 - Google脚本

时间:2017-01-11 22:51:19

标签: google-apps-script

我正在尝试编写一个脚本来归档在另一个文件夹中找到的文件,但是我无法将类型从FolderIterator更改为Folder类型。

//Global Variables
var classroomFolderName = "Classroom";
var archiveFolderName = "Test Archive";

以下代码检查以确保在脚本开始执行之前文件夹已存在

function doGet(){
  //Makes sure there is an Classroom folder available 
  try {    
    getFolder(classroomFolderName);
  }

  catch(e){
    if (e == 1){
      Logger.log("Error 1: Classrooms folder not found");
      return ContentService.createTextOutput("Error 1: Classrooms folder not found"); 
    }

    else if (e == 2){
      Logger.log("Error 2: Multiple Classroom folders found");
      return ContentService.createTextOutput("Error 2: Multiple Classroom folders found");
    }
  }

  //Makes sure there is an Archive folder available 
  try {
    getFolder(archiveFolderName);
  }

  catch(e){
    if (e == 1){
      //Rather than returning an error, the new archive folder is created
      DriveApp.createFolder(archiveFolderName);
    }

    else if (e == 2){
      Logger.log("Error 3: Multiple Archive folders found");
      return ContentService.createTextOutput("Error 3: Multiple Archive folders found");
    }
  }

这是我遇到麻烦的部分。我想在这些迭代器中的文件夹上使用Folder类功能。每个迭代器只包含1个文件夹,我无法访问该文件夹。

  var classroomFolder = getFolder(classroomFolderName);
  var archiveFolder = getFolder(archiveFolderName);


}

用于检查文件存在的函数

function getFolder(folderName){
  var foldercount = 0;
  //Selects all folders named exactally as parameter is given
  var folder = DriveApp.getFoldersByName(folderName);
  while (folder.hasNext()) {
    var folders = folder.next();
    foldercount++;
  }

  //Throws errors if number of folders != 1
  if (foldercount < 1){
    throw 1;
  }

  else if (foldercount > 1){
    throw 2;
  }

  else{
    return folder;
  }
}

1 个答案:

答案 0 :(得分:0)

Woops,我的错误,我在getFolder函数中清空迭代器,却没有意识到。

使用以下代码修复它。

  var classroomFolder = DriveApp.getFoldersByName(classroomFolderName).next();
  var archiveFolder = DriveApp.getFoldersByName(archiveFolderName).next();