10

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

1
  • DocsList is deprecated.
    – Wicket
    Commented May 3, 2018 at 0:38

5 Answers 5

6

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);
}
2
  • 1
    This is what I do as well, but I found that getFoldersByName(fdr_name).next() was not returning an error when there was no match. I ended up adding "var name=newFdr.getName()" in the try: section to force a failure. That seemed to fix my problem, but I'm still not quite sure why it was needed.
    – Craig
    Commented Mar 4, 2017 at 22:21
  • Thanks! It took me a while of Googling to finally find this answer, and now my script works.
    – Ryan
    Commented May 13, 2017 at 1:09
5

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!

1
  • Small correction: 'var folderName = getFolders(parent_folder,name);' should be 'var folderName = getFolder(parent_folder,name);'
    – MickeDG
    Commented Jun 5 at 8:10
5

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);
1
  • Using this answer in 2020 with the V8 engine, be aware that replacing 'var folderalumno' with 'let' or 'const' creates closure problem... declare folderalumno before the 'try' and assign the values in the try-catch.
    – Ron
    Commented Nov 24, 2020 at 13:23
5

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");
0

If someone is still looking for answer on this question and want to cerate folder if it doesn`t exist here is function I have created.

This function accepts two input values:

  • base_folder - folder ID in which to perform a search or false to search folders in Drive root folder
  • folder_name - folder name that you are searching for

There is some things that can be adjusted, but I have using this to create folder structure base folder -> year -> month -> day.

function checkFolders(base_folder, folder_name) {
  if (base_folder){ //Checks if is specified main folder
    var folders = DriveApp.getFolderById(base_folder).getFolders(); //Getting folder list from specified location
  } else { //If not specified folder we take all Drive folders
   var folders = DriveApp.getFolders(); //Getting all folders in Drive
  }

  var folder_exist = false, folder; //By default folder don`t exists till we check and confirm that it exists

  while(folders.hasNext()){ //Looping through all folders in specified location while we have folders which to check
    folder = folders.next(); //Taking next folder to check if it is folder that we are looking for
    if(folder.getName() == folder_name){ //Checking it`s name
     folder_exist = folder.getId(); //If folder is found we assign its ID to our return variable
    } //If folder don`t exists we have already assigned false to return value
  }

  if (!folder_exist) { //Checks if folder don`t exists than we need to create it
    if(base_folder){ //Checking where we should create folder
      DriveApp.getFolderById(base_folder).createFolder(folder_name); //If base folder is specified than we create there folder
    } else {
      DriveApp.createFolder(folder_name); //If base folder not specified than we create folder in Drive root folder
    }
   folder_exist = checkFolders(base_folder, folder_name); //Now run self again to check if folder was created and if it is created than we get folder ID
  }

  return folder_exist; //Returning false if our folder is not created or folder ID if folder exists and is created
}

This is how I`m using this function:

function createFolderStructure() {
 var base_folder_id, year_folder_id, month_folder_id, day_folder_id, date, day, month, year;

 date = new Date(); //Creates new Date object
 day = date.getDate(); //Extract day number in month
 month = date.getMonth(); //Extract month number, first month number is 0
 year = date.getFullYear(); //Extract year number

 base_folder_id = checkFolders(false, "My base folder"); //Check if base folder is created, if created return folder ID, if not, than create it and return it ID
 year_folder_id = checkFolders(base_folder_id, year); //Check if year folder is created, if created return folder ID, if not, than create it and return it ID
 month_folder_id = checkFolders(year_folder_id, month); //Check if month folder is created, if created return folder ID, if not, than create it and return it ID
 day_folder_id = checkFolders(month_folder_id, day); //Check if day folder is created, if created return folder ID, if not, than create it and return it ID, ID can be used to save files in this folder
}
2
  • Tried this code and works as expected but the issue is that it take 4 times as long and perhaps will take even longer with more folders in the drive. Not sure if anybody can get around this :/
    – asreerama
    Commented Dec 16, 2020 at 8:11
  • Sorry, but in my case, it will create max 24 folders per day and not in the same time. I'm not sure if it is related to the number of folders you have in your drive. I see that this can be improved. Maybe DriveApp.getFolders() is taking a lot of time. I would make one function call and give a date object or array with day, month, year, and get folders only once. I think it will speed up, don`t know how much faster it will be. If you still need help with this, tomorrow I can try and update this function, and you can check if it works faster or not.
    – krismans
    Commented Jan 13, 2021 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.