apps-script - Create new google doc in existing folder - google-apps-script

I am creating a google doc from apps script as follows:
var newDoc = DocumentApp.create(docName);
I want this new document to be created in an existing folder in my drive. I tried the following way:
var dir = DriveApp.getFolderById("folder-id");
dir.addFile(newDoc);
But I get the error as:
ReferenceError: "DocsList" is not defined.
Is there any way to create a new document in my existing folder or move my file to an existing folder via apps script? Any help will be appreciated.

Folder.addFile() requires that you pass it a File, but DocumentApp.create() returns a Document. What you need to do is use newDoc.getId() to get its unique identifier, and then use it in DriveApp.getFileById() to properly move the file.
var newDoc = DocumentApp.create(docName); // Create a Document
var docFile = DriveApp.getFileById(newDoc.getId()); // Get Document as File
var dir = DriveApp.getFolderById("folder-id"); // Get the folder
dir.addFile(docFile); // Add the file to the folder
DriveApp.getRootFolder().removeFile(docFile); // Optionally remove the file from root
Please also note that Google Drive files can exist in multiple folders. So if you only want the file to be listed in the "folder-id" folder, then you'll need to remove it from the root folder where it was created by default.

Related

Modify Google App Script - Gmail to Google Drive

I'm trying to modify this script found here:
https://github.com/ahochsteger/gmail2gdrive
I need the script to check if the file already exists on Google Drive and if not, create it. Currently, the script just creates the file into Google Drive, without checking to see if an existing file with the same name already exists or not.
I'm not a programmer, I know nothing about Google App Script (although I have managed to set it up and got it running) and I know nothing about JavaScript. I'm just wondering if someone could either point me in the right direction or help me code this one feature that I need?
From what I understand (I could be wrong), the attachment is created based on this line in the code:
var file = folder.createFile(attachment);
So then I tried add this before the createFile:
var file = folder.removeFile(attachment);
My logic here is that if the file exists in the folder, then remove it first before creating it (therefore avoiding duplicate files). But that didn't work.
From the script of GitHub in your question, it is found that attachment is blob. So how about using this filename? I think that there are several solutions for your situation. So please think of this as one of them. The flow of sample script is as follows.
Retrieve the filename of blob.
Retrieve FileIterator using getFilesByName().
If the FileIterator has values, it means that the file with the same filename has already been existing.
If the FileIterator has no values, it means that the file with the same filename is not existing.
The sample script is as follows.
Sample script 1:
If you want to create new file only when the file of same filename is not existing, you can use the following script.
var fileName = attachment.getName();
var f = folder.getFilesByName(fileName);
var file = f.hasNext() ? f.next() : folder.createFile(attachment);
Sample script 2:
If you want to do something when the file of same filename is existing, you can use the following script.
var fileName = attachment.getName();
var f = folder.getFilesByName(fileName);
var file;
if (f.hasNext()) {
// If the file has already been existing, you can do something here.
} else {
// If the file is not existing, you can do something here.
file = folder.createFile(attachment);
}
Note:
From your question, the file is searched from the folder. If you want to search the file from all files, please tell me.
References:
getName()
getFilesByName(name)
FileIterator
If this was not what you want, please tell me. I would like to modify it.

Google script Create new sheet file and move it to a specific folder Then copy the contents and 2 tabs from the active sheet to the newly created file

Welcome: I will not go into the code at the beginning, but I would like to ask a few questions. To learn the logic of operation.
Question 1:
When I create a new file using the function
var newFile = SpreadsheetApp.create("Name new sheets")
var newFileId = newFile.getId()
A new file is always saved to the root directory of the google disk?
Question 2
If I always write root directory of the google disk.The only way to move a newly created file is to use
var TARGE_FOLDER_ID = "asdFHd4hasdasn6nJMGLSQt8das331"
DriveApp.getFileById(newFileId).makeCopy("Name new sheets",TARGE_FOLDER_ID);
And after copying the removal from the main google drive folder?
When I create a new file using the function
Yes SpreadsheetApp.create("Name new sheets") puts files in the root directory you will have to move them
If I always write root directory of the google disk.The only way to move a newly created file is to use
Yes something like this Move file
var folder=DriveApp.getFoldersByName(folderName).next();//gets first folder with the given foldername
var file=SpreadsheetApp.create(fileName);
var copyFile=DriveApp.getFileById(file.getId());
folder.addFile(copyFile);
DriveApp.getRootFolder().removeFile(copyFile);

Acquiring the Google Drive folder my google script is located

With the help of a nice article (https://www.labnol.org/internet/google-drive-tree/21198/), I just setup my first google script in Google Drive.
Quick Question:
How may I get a running script /myFolder1/music/myFirstScript.gs, to determine it's running in /myFolder1/music?
This didn't work. I got the Url but nothing in the log file showed the correct answer.
var files = DriveApp.searchFiles('title contains "GoogleTreeAgenda5"');
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
Logger.log(file.getUrl());
Logger.log(file.getDownloadUrl());
Logger.log(file.getDescription());
Logger.log(file.getOwner());
Logger.log(file.getParents());
Logger.log(file.getParents()[0].getName());
Logger.log("------------------------------");
}
Longer Behind The Scenes Reason:
The file will be modified a bit so that each month I will create a new tree structure off the root with agenda topics and the script will create an html file from the directory tree which is based on topic. Basically it will be an outline creator based on the current location of the script file. So Let's say this month it's in: /myFolder1/music (so in other words it's /myFolder1/music/myFirstScript.gs. The script needs to determine that folder is /myFolder1/music so that I can have it print the tree structure starting from the folder it's located in to an html file..
In the example application provided by the site I noted above, there are 2 options to print the tree from the google script:
1) Tree starting from the root folder
var parentFolder = DriveApp.getRootFolder();
2) Starting from a particular folder (but I can't figure out and will need "Folder_Name" to be determined dynamically from the location where the .gs file is located)
var parent = DriveApp.getFoldersByName("FOLDER_NAME").next();
I've used getScriptId() this will:
Gets the script project's unique id.
This id is also the unique id in the Google Drive. Then from there, create a recurring getParents() until you reach the root folder.
Here is the complete code:
function myFunction() {
var scriptID = ScriptApp.getScriptId();
// Logger.log(scriptID)
// Log the name of every parent folder
var driveFile = DriveApp.getFileById(scriptID);
var parentFolder = driveFile.getParents();
while (parentFolder.hasNext()) {
var folder = parentFolder.next();
Logger.log(folder.getName());
}
}
NOTE:
There is no real or concrete path since a file can have multiple parents. It is also stated here in this related SO post.
Hope this helps.

Spreadsheet creation - Permissions, file location and remove file

I have an Adwords script that creates a new spreadsheet by using the command below:
var ssNew = SpreadsheetApp.create("Name document");
Is it possible to create this file in a specific folder of my Google Drive?
If so; the file will have the default access (view, edit, comment) permissions as the folder has, right?
If not; is it possible to give the created file a permission as in "Everyone in [company] can edit this file"?
Furthermore, is it possible to set some sort of expiration date for the file?
I'm planning on running the script daily and old files will no longer be relevant.
I can build some sort of check to find the old file, delete it and then run the script again, but if there is some sort of expiration function that would save me quite some code.
Thanks!
It is apparently not possible to create Spreadsheets within folders.
You'll have to use something like this:
function createNewSpreadsheetinFolder(){
var ssNew = SpreadsheetApp.create("Name document");
var targetFolder = DriveApp.getFolderById("0B1TY_1aqz3fpWktMa25LbVkzQTQ");
var ssnewFile = DriveApp.getFileById(ssNew.getId());
var ssFinal = ssnewFile.makeCopy("Name document", targetFolder);
ssnewFile.setTrashed(true);
try {ssFinal.addViewers(targetFolder.getViewers())} catch(e){};
try {ssFinal.addEditors(targetFolder.getEditors())} catch(e){};
}

google drive scripting folder location

I have a GApp which scratch builds a new GDrive spreadsheet. I shows up in my root directory.
I would like to place the new SS in a specific folder instead.
I cannot seem to find how to accomplish this.
From the API Reference
// This example creates a new file and adds it to a folder
// Note: This can also be used on a folder to add it to another folder
var file = DocsList.createFile('my test file', 'test file contents');
var folder = DocsList.createFolder('My Test Folder');
file.addToFolder(folder);
Logger.log(file.getParents()[0].getName()); // logs 'My Test Folder'
Just a heads up, depending on how you create your spreadsheet you might have difficulties, DocumentApp.create() and file appear to be different object types. But no worries, file has its own create method (DocsList.createFile(name, contents)) which can be referenced here
Hope that helps.