DriveApp.GetFoldersByName() always returning true

2019-07-28 02:24发布

问题:

I've been playing around with google drive scripts.

I need to create a folder from a spreadsheet in case a folder with that name doesn't exist.

The problem though, is that it says the folder exists even if it doesn't.

The check is inside a try function .

Like this :

try {
   //currentName is the name of the folder and it's working properly
   var folder = DriveApp.getFoldersByName(currentName);
   Logger.log('That folder already exists!')
} catch(err) {
   var folder = DriveApp.createFolder(currentName);
   Logger.log('Folder created because it didnt exist');
}

Any reason why it always finds a folder even if it doesn't exist ?

It worked fine on top of my drive. But then I placed it inside a server drive that has a lot of folders. Is it a permissions problem? Or I'm not retrieving the current folders in the server?

Am I missing any type of checks?

回答1:

Find out the problem.

DriveApp.getFoldersByName returns a FolderIterator, so I must do an extra test after that.. Like this :

var folder = DriveApp.getFoldersByName(currentClient);
if(folder.hasNext()) {
    Logger.log('File already exists')
} else {
    var folder = DriveApp.createFolder(currentClient);
    Logger.log('New folder created!');
}

It worked perfectly like this.