how to Create a folder if it does not exist? - google-apps-script

I am creating a script to add a folder on all subfolders if the folder is not existing. But unfortunately, I am generating only on one folder. How to make this changes under a parentfolder? Thank you for your answers.
Here is my code:
function folder_create(){
var foldername = 'CHECK FOLDS';
var folders = DriveApp.getFoldersByName(foldername);
var foldersnext = folders.next();
var subfolders = foldersnext.getFolders();
var subfolders = subfolders.next();
var files = subfolders.searchFolders("title contains 'Testing Test'");
{
while(files.hasNext()){
var reportFolderExist = files.next();
var yearFolders = reportFolderExist.getFoldersByName("TESTTT");
if(yearFolders.hasNext()){
} else {
reportFolderExist.createFolder("testing only----");
}
}
}}

Current situation:
If I understand you correctly, this is your current situation:
You have a main folder called CHECK FOLDS.
This main folder contains several subfolders.
For each of these subfolders, you want to check whether they contain a folder whose title contains Testing Test.
If the subfolder doesn't contain a Testing Test folder, create it.
Issue and solution:
If this is correct, the main issue in your code is that you are not iterating through all subfolders, but only accessing the first one var subfolders = subfolders.next();. You should use a loop instead, in order to check each subfolder (see code sample below).
Also, your code contains some confusing parts, like iterating through files (that is Testing Test folders) and looking for folders called TESTTT inside of these files. I don't think this makes sense, if the current situation is the one I described above.
Code sample:
function folder_create(){
var foldername = 'CHECK FOLDS';
var folders = DriveApp.getFoldersByName(foldername);
var foldersnext = folders.next(); // Main folder
var subfolders = foldersnext.getFolders();
while (subfolders.hasNext()) { // Loop through subfolders
var subfolder = subfolders.next(); // Subfolder
var files = subfolder.searchFolders("title contains 'Testing Test'");
if (!files.hasNext()) { // Check if "Testing Test" exists.
subfolder.createFolder("Testing Test"); // Create "Testing Test" folder inside subfolder
}
}
}

Related

How can I modify this to save a spreadsheet into a new folder

I've found scripts that save a copy of a spread sheet, but so far I've not been able to figure out how to modify the following code to save my spreadsheet into the newly created/already existing folder.
//Create folder if it does not exist
function createFolder(folderID, folderName){
var parentFolder = DriveApp.getFolderById(folderID);
var subFolders = parentFolder.getFolders();
var doesntExist = true;
var newFolder = '';
// Check if folder already exists.
while(subFolders.hasNext()){
var folder = subFolders.next();
//If the folder exists return the id of the folder
if(folder.getName() === folderName){
doesntExist = false;
newFolder = folder;
return newFolder.getId();
};
};
//If the folder doesn't exist, then create a new folder
if(doesntExist == true){
//If the file doesn't exist
newFolder = parentFolder.createFolder(folderName);
return newFolder.getId();
};
};
function start(){
var FOLDER_ID = 'my folder id';
var NEW_FOLDER_NAME = SpreadsheetApp.getActiveSheet().getRange('A1').getValue();
var myFolderID = createFolder(FOLDER_ID, NEW_FOLDER_NAME);
};
Update:
My goal is to create a new folder based on the contents of cell A1 if that folder doesn't exist and save the file in that folder. If the folder already exists, then save the file in the existing folder. The file name will be in cell A2.
I want to save a copy, and leave the original file where it is.
Since September 30, 2020, Drive files cannot have multiple parent folders.
Therefore, you should either move your file to the new folder, or make a copy of the file. But you cannot have the same file in two different folders.
You should use either moveTo(destination), if you want to move the file to the new folder, or makeCopy(destination) if you want to copy your file to the new folder.
Update: You mentioned in comments that you want to make a copy the file (not move it) and specify the name of the copied file (corresponding to value in A2). Therefore, you should use makeCopy(name, destination).
Considering that you want to save the active spreadsheet, your main function could be like this:
function start(){
var PARENT_FOLDER_ID = 'my folder id';
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var NEW_FOLDER_NAME = sheet.getRange('A1').getValue();
var FILE_NAME = sheet.getRange('A2').getValue();
var spreadsheetId = ss.getId();
var file = DriveApp.getFileById(spreadsheetId);
var folder = createFolder(PARENT_FOLDER_ID, NEW_FOLDER_NAME);
file.makeCopy(FILE_NAME, folder);
}
And the function createFolder could be greatly reduced in size, using Folder.getFoldersByName(name):
function createFolder(folderID, folderName){
var parentFolder = DriveApp.getFolderById(folderID);
var subFolders = parentFolder.getFoldersByName(folderName);
if (subFolders.hasNext()) return subFolders.next(); // Return existing folder
else return parentFolder.createFolder(folderName); // Return created folder
}
Notes:
Because of this behaviour change in Drive, methods like addFile(child) are deprecated.
Reference:
Single-parenting behavior changes
The script in your example creates a new folder. It doesn't save anything, as far as I can tell.
If you want just save your current spreadsheet in some already existing folder, here you go:
var id = SpreadsheetApp.getActiveSpreadsheet().getId();
var file = DriveApp.getFileById(id);
var folder = DriveApp.getFolderById("FOLDER_ID"); // <-- ID of the destination folder
folder.addFile(file);
Update. In case you know the name of destination folder and the folder shares the same parent folder with current spreadsheet file the script can look like this:
var ss = SpreadsheetApp.getActiveSheet();
var dest_folder_name = ss.getRange('A1').getValue();
var copy_name = ss.getRange('A2').getValue();
var dest_folder = "";
var file_id = SpreadsheetApp.getActiveSpreadsheet().getId();
var file = DriveApp.getFileById(file_id);
var parent_folder = file.getParents().next();
var sub_folders = parent_folder.getFolders();
// search a destination folder in current folder
while (sub_folders.hasNext()) {
dest_folder = sub_folders.next();
if (dest_folder.getName() === dest_folder_name) {
break;
}
dest_folder = "";
}
// create the destination folder if nothing was found
if (dest_folder === "") {
dest_folder = parent_folder.createFolder(dest_folder_name);
}
// copy the spreadsheet to the destination folder
file.makeCopy(copy_name, dest_folder);
The script tires to finds destination folder (the name taken from cell 'A1') inside current folder and creates the folder if nothing was found. After that it saves a copy of current spreadsheet (the name taken from cell 'A2').
NB. GoogleDrive allows files or subfolders with the same names inside one folder. So it's not unlikely to get many spreadsheets with identical names. Perhaps it makes sense to check names of existing files before the saving.

duplicate folder and rename file structure

I'm trying to automate my duplicating folder process in google drive. As part of the process, I want to rename files and folders for each new client.
I've adapted some code found previously. It was previously working well, but for some reason now any folders/files that are more than 1 level deep of the root folder come back "undefined" in the replace section of the command.
function duplicatefolder(){
var newclientname = Browser.inputBox('Client Name')
var sourceFolder = "1. Master Client Folder";
var targetFolder = newclientname;
var source = DriveApp.getFoldersByName(sourceFolder);
var target = DriveApp.createFolder(targetFolder);
if (source.hasNext()) {
copyFolder(source.next(), target, newclientname);
}
}
function copyFolder(source, target,client) {
var folders = source.getFolders();
var files = source.getFiles();
while(files.hasNext()) {
var file = files.next();
var newname= file.getName().toString().replace("Master",client)
file.makeCopy(newname, target);
}
while(folders.hasNext()) {
var subFolder = folders.next();
var folderName = subFolder.getName();
var newFolderName = subFolder.getName().replace("Master",client)
var targetFolder = target.createFolder(newFolderName);
copyFolder(subFolder, targetFolder);
}
}
The script also creates the folder in the root directory of google drive. Ideally, I'd like it to be created inside the folder "Clients". How would I add this to the script?
Appreciate the help.
Cheers
Please see attached link hope this is it what you are looking for
https://yagisanatode.com/2018/07/08/google-apps-script-how-to-create-folders-in-directories-with-driveapp/

In Google-App-Script for Google Drive how do I move certain files from root to a certain folder if their title includes a certain word?

I want to use Google-App-Script to move certain files into a specific folder if their title contains a certain word
I have tried something like this but the error message states that the method is not defined. Any pointers/suggestions?
This is my code:
function myFunction() {
var searchFor ='title contains "Copyright"';
var names =[];
var files = DriveApp.searchFiles(searchFor);
var destination = DriveApp.getFolderById("1xN0AUclE2t9yqlNzTwgRup3nn7G0Qsik");
while (files.hasNext()) {
files.next().destination.addFile(file);
}
}
It looks like you did not define the "file" variable anywhere in your code.
You can either define it in your while loop, or pass files.next() as an argument to addFile().
Finally, you should remove files.next() from the beginning of line 7, as this chaining is incorrect and is likely causing your error!
Also, note that the file will not be removed from its original folder, but will be accessible from both locations. If you wish to remove the file from the original location, let me know and I will edit my code to add this.
Try this:
function myFunction() {
var searchFor ='title contains "Copyright"';
var names =[];
var files = DriveApp.searchFiles(searchFor);
var destination = DriveApp.getFolderById("1xN0AUclE2t9yqlNzTwgRup3nn7G0Qsik");
while (files.hasNext()) {
var file = files.next();
destination.addFile(file);
}
}
or this:
function myFunction() {
var searchFor ='title contains "Copyright"';
var names =[];
var files = DriveApp.searchFiles(searchFor);
var destination = DriveApp.getFolderById("1xN0AUclE2t9yqlNzTwgRup3nn7G0Qsik");
while (files.hasNext()) {
destination.addFile(files.next());
}
}
Note that your code doesn't do what you say it does. Namely, it doesn't actually 'move' files from the root folder to the specified folder (if that's what you want to accomplish).
In Google Drive, folders and files can have more than one parent. Think of folders as 'labels' applied to files and other folders. Calling the addFile(file) method of the Folder class will add the file to the new folder but that same file will also remain in its original parent folder(s).
This could cause problems as you may accidentally remove the file from one of the folders thinking it's a copy when in fact it's the same file stored in multiple folders.
Since there's no direct way to 'move' the file to another folder in Google Drive, the actual process consists of 2 steps.
Getting the list of parent folders for the file:
var folderIterator = file.getParents();
Adding the file to the destination folder and removing it from the previously saved parent folders
targetFolder.addFile(file);
//Remove from parents
while (folderIterator.hasNext()) {
folderIterator.next().removeFile(file);
}

Move Folder Using App Script

So i'm brand new to JS and trying to build a program for internal operation at the company I work for. Below is the first bit of my code. I have a created a google form, and set a trigger so that when the submit button is clicked the below code will start. The trigger works and the first two functions work, but I cannot seem to get the Karrie folder to move from the root to the sub folder id (I do have the correct ID but omitted it from this post). Maybe I'm doing this all backwards so any help would be appreciated.
// Create Karrie Folder In Root
function start() {
var sourceFolder = "Property Template";
var targetFolder = "Karrie";
var source = DriveApp.getFoldersByName(sourceFolder);
var target = DriveApp.createFolder(targetFolder);
if (source.hasNext()) {
copyFolder(source.next(), target);}}
// Adds Property data to Karrie Folder
function copyFolder(source, target) {
var folders = source.getFolders();
var files = source.getFiles();
while(files.hasNext()) {
var file = files.next();
file.makeCopy(file.getName(), target);}
// Adds Photo Folders to Karrie Folder
while(folders.hasNext()) {
var subFolder = folders.next();
var folderName = subFolder.getName();
var targetFolder = target.createFolder(folderName);
copyFolder(subFolder, targetFolder);}}
// Moves Karrie folder to propertie folder
function MoveFiles(){
var files = DriveApp.getFolderByName("Karrie");
var destination = DriveApp.getFolderById("ID NA");
destination.addFolder(files);}
Debugger
I understood that MoveFiles() in your script doesn't work. If my understanding is correct, how about this modification?
Modification points :
In order to move a folder, it required to move the parent of the folder.
But when addFolder() is used to the folder, the folder has 2 parents.
So original parent has to be removed.
There is no getFolderByName(). Please use getFoldersByName().
Modified script :
function MoveFiles(){
var folder = DriveApp.getFoldersByName("Karrie").next();
var destination = DriveApp.getFolderById("ID NA");
destination.addFolder(folder);
folder.getParents().next().removeFolder(folder);
}
Note :
In this script, The folder and parent of "Karrie" supposes only one in the Google Drive, respectively.
References :
getFoldersByName()
addFolder()
removeFolder()
If I misunderstand your question, please tell me. I would like to modify it.
Edit 1 :
When you run this function, does the ID of Logger.log(r) show the folderId of "Karrie"?
function sample() {
var r = DriveApp.getFoldersByName("Karrie").next().getId();
Logger.log(r)
}
Edit 2 :
Please confirm and consider the following points.
Confirm the folder name and the existence of the folder again.
Run sample() and confirm folder ID of "Karrie".
Confirm whether there are no functions with the same name.
Can I ask you the folder ID of "Karrie"? If you cannot retrieve the folder ID using DriveApp.getFoldersByName("Karrie").next().getId(), I propose to use directly the folder ID of "Karrie".
Updated on March 30, 2022:
In the current stage, the files and folders can be moved using moveTo. Ref This method has added on July 27, 2020. When moveTo is used, the above script can be modified as follows.
function MoveFiles(){
var folder = DriveApp.getFoldersByName("Karrie").next();
var destination = DriveApp.getFolderById("ID NA");
folder.moveTo(destination);
}
Reference:
moveTo(destination) of Class Folder
As of 2020, the easier way I found to move a file is to use this function:
function moveToFolder(file, sourceFolder, destFolder) {
var file = DriveApp.getFileById(file.getId());
destFolder.addFile(file);
sourceFolder.removeFile(file);
}
Because of the first line, you can convert your Spreadsheet, Google Form, Document or others Google objects into a File.
Then we just use methods of the Folder class : https://developers.google.com/apps-script/reference/drive/folder
Notes:
If you created your file by using .create() your sourceFolder will be DriveApp.getRootFolder().
If you have multiple files to move, just iterate over them.

How can I pull information from spreadsheets in multiple folders in google script?

I already have a script which references all documents in ONE folder, but I need to reference multiple folders...
Script that works for one folder is:
var folder = DocsList.getFolder("My Spreadsheets");
var contents = folder.getFiles();
What I WANT to do is either
var masterfolder = DocsList.getFolder("My Folder that has multiple folders");
var folder = DocsList.getFolders(masterfolder)
var contents = folder.getFiles();
or
var folder = DocsList.getFolder("My Spreadsheets", "My Other Spreadsheets");
var contents = folder.getFiles();
I am quite newbye in this, but I think you'll have to do an iteration throught the subfolders:
var folder = DocsList.getFolders(masterfolder)
Here you dont't get one single folder; you get a set of them and you have to iterate trhout it with a for bucle. Something like:
for f in folders {
f.getfiles......
...
}
SURE you will get more precise answer.
Enrique