I successfully use the following code from ctrlq.org to create folders in Google Drive:
function go() {
var path = "//main//parent//child//grandchild”;
var folder = getDriveFolder(path);
Logger.log(folder.getUrl());
}
function getDriveFolder(path) {
var name, folder, search, fullpath;
// Remove extra slashes and trim the path
fullpath = path.replace(/^\/*|\/*$/g, '').replace(/^\s*|\s*$/g, '').split("/");
// Always start with the main Drive folder
folder = DriveApp.getRootFolder();
for (var subfolder in fullpath) {
name = fullpath[subfolder];
search = folder.getFoldersByName(name);
// If folder does not exit, create it in the current level
folder = search.hasNext() ? search.next() : folder.createFolder(name);
}
return folder;
}
I am running into an error in one of my sheets. after the last folder(grandchild) gets created, one additional folder is created also.
The name of the folder is: function (search) { if (search == "") { return false; } for (var i = 0; i < this.length; i++) { if (this[i] == search) { return i; } } return -1;}
Yes, that is literally the name of the folder created at the end of every path created with the function with this one spreadsheet. It was driving me nuts.
Through trial and error, I have discovered that the having the following code in my project causes this additional folder to be created.
Here is the code that causes the problem:
Array.prototype.findIndex = function(search){
if(search == "") return false;
for (var i=0; i<this.length; i++)
if (this[i] == search) return i;
return -1;
}
Is it possible to rewrite the getDriveFolder to prevent this from happening? Maybe even just by filtering out the name? I have tried to no avail. Your help is greatly appreciated.
I ended up solving this one myself. It's probably not the best solution, but it works. I added the following code to filter out the bad folder name.
if(folderName.indexOf("function (search") > -1) {
var folderParent = DriveApp.getFolderById(folderID).getParents().next();
DriveApp.getFolderById(folderID).setTrashed(true);
folder = folderParent;