I have the following script:
function createOrGetFolder(folderName, parentFolderId) {
try {
var ssid = SpreadsheetApp.getActiveSpreadsheet().getId();
var folders = DriveApp.getFileById(ssid).getParents();
pastavideo = folders.next().getParents().next();
var foldersIter = pastavideo.getFoldersByName("01-01"),
parentFolder = DriveApp.getFolderById(parentFolderId),
folder;
if (parentFolder) {
if (foldersIter.hasNext()) {
folder = foldersIter.next();
} else {
folder = parentFolder.createFolder("Video").createFolder("01-01");
}
} else {
throw new Error("Parent Folder with id: " parentFolderId " not found");
}
return folder.getId();
} catch (error) {
return error;
}
}
My folder structure is as follows
parentFolder > Video > 01-01
The idea is that this script checks if the Video
folder and the 01-01
folder exist, if they don't exist I want it to create them.
The problem is that the way the script is written it is not doing the verification, just creating several folders Video
and 01-01
inside the parent folder.
How can I resolve this?
CodePudding user response:
As I mentionned in the comment, I think the code provided is on the right way, it still lacks a few lines to be ordered, try this:
var foldersIter = pastavideo.getFoldersByName("01-01")
is changed to var foldersIter = parentFolder.getFoldersByName("Video")
Then, inside the if (parentFolder) block, make sure that the foldersIter object has a next element. If it does, assign it to the folder variable. If not, create a new folder "Video" in the parentFolder, then create a new folder "01-01" in the folder "Video".
function createOrGetFolder(folderName, parentFolderId) {
try {
var ssid = SpreadsheetApp.getActiveSpreadsheet().getId();
var folders = DriveApp.getFileById(ssid).getParents();
var parentFolder = DriveApp.getFolderById(parentFolderId),
folder;
if (parentFolder) {
var foldersIter = parentFolder.getFoldersByName("Video");
if (foldersIter.hasNext()) {
video_folder = foldersIter.next().getFoldersByName("01-01");
if (video_folder.hasNext()) {
folder = video_folder.next();
}
} else {
folder = parentFolder.createFolder("Video");
folder = folder.createFolder("01-01");
}
} else {
throw new Error("Parent Folder with id: " parentFolderId " not found");
}
return folder.getId();
} catch (error) {
return error;
}
}