How to create a folder if it doesn't exist?

2019-02-21 17:38发布

I'm trying to create a folder if it doesn't exist, but the code creates a new folder every time I run it. I don´t know if my code is right.

Here is my code:

var alumnopath = DocsList.getFolderById ('0Bzgw8SlR34pUbFl5a2tzU2F0SUk');
var alumno2 = alumno.toString();
Logger.log(alumno2);
try {
  var folderalumno =  alumnopath.getFolder(alumno2);
  if (folderalumno == undefined){
    var folderalumno =  alumnopath.createFolder(alumno2);
  }
  else {
    var folderalumno =  alumnopath.getFolder(alumno2);
  }
}
catch(e) {
  var folderalumno =  alumnopath.createFolder(alumno2);
}
folderalumno.createFile(pdf.getAs('application/pdf')).rename(  alumno +  " , " + fechafor);

Thanks for your help!!

4条回答
▲ chillily
2楼-- · 2019-02-21 17:56

You actually don't need the if condition when you use a try/catch structure. The try/catch structure handles the case where the folder doesn't exist by itself.

Try it like this:

var alumnopath = DocsList.getFolderById ('0Bzgw8SlR34pUbFl5a2tzU2F0SUk');
var alumno2 = alumno.toString();
Logger.log(alumno2);
try{
  var folderalumno =  alumnopath.getFolder(alumno2);
}
catch(e) {
  var folderalumno =  alumnopath.createFolder(alumno2);
}
folderalumno.createFile(pdf.getAs('application/pdf')).rename(  alumno +  " , " + fechafor);
查看更多
ゆ 、 Hurt°
3楼-- · 2019-02-21 18:09

As of Google Apps Script code in 2016 Aug

var par_fdr = DriveApp.getFolderById(123456789A); // replace the ID
var fdr_name = "child_fdr";

try {
  var newFdr = par_fdr.getFoldersByName(fdr_name).next();
}
catch(e) {
  var newFdr = par_fdr.createFolder(fdr_name);
}
查看更多
戒情不戒烟
4楼-- · 2019-02-21 18:15

Google has changed its scripting. I know this is an old post but this is the best current answer I could come up with:

function getFolder(parent_folder,folder_name){
  var folders = parent_folder.getFolders();     
  while (folders.hasNext()) {
    var folder = folders.next();
    if(folder_name == folder.getName()) {         
      return folder;
    }
  }
  return false;
}

var parent_folder = DriveApp.getFolderById(//id\\);
var folderName = getFolders(parent_folder,name);
if (folderName === false){
  folderName =  outputfolderId.createFolder(name);
}

Hope this helps someone else!

查看更多
我想做一个坏孩纸
5楼-- · 2019-02-21 18:21

In case anyone else runs in to this issue, you can use the ternary operator like this (replacing the "Name_of_Folder" string as needed):

var alumnopath = DriveApp.getFoldersByName("Name_of_Folder");
var folderalumno = alumnopath.hasNext() ? 
    alumnopath.next() : DriveApp.createFolder("Name_of_Folder");
查看更多
登录 后发表回答