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){};
}
Related
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.
My google app script stop work after a certain times. the following code changes the file permission. in my folder there is like 10K files. when i run the script after changing 1~2K file sharing permission script stop work. is there anyway to solve the issue?
function myFunction() {
var folderId = "ID";
var files = DriveApp.getFolderById(folderId).getFiles();
var result = [];
while (files.hasNext()) {
var file = files.next();
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
var temp = {
file_name: file.getName(),
url: "http://drive.google.com/uc?export=view&id=" + file.getId(),
};
result.push(temp);
};
}
There are several workarounds, from upgrading your account to grant access to longer timeouts, you could also make the script work with a cache service and store the state of the iteration before the timeout, then run again the script with this value stored on the cache.
Although, all of this may be to much for what you are attempting to: permissions on Drive have inheritance.
What does this mean? This means that if you change the permission settings on any folder you'll override the permissions of each file on that folder.
In summary, you really do not need to make any iteration thru all the files, change the permissions for that folder and you are done.
Check this docs in case of doubt.
A working code to change your folder permission and all its contained files:
function myFunction() {
var folder = DriveApp.getFolderById("YOUR_FOLDER_ID");
folder.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
}
This works, but due to the large number of files on your folder propagation may take some time, up to several hours, be patient and check it tomorrow.
As title suggests
Got a script that's fetching a CSV from a specific G-Drive folder, which is currently filtering by a specific file name.
Is it possible to just say 'get the latest file' from that folder instead of searching by the specific name?
Asking because multiple copies of the same file will be uploaded into the same folder (file name is content.csv, copies will either replace that file, or no doubt be uploaded as content(1).csv etc). So, therefore, assumed just trying to 'get the latest file' would be the best way?
Script:
function importCSVFromGoogleDrive() {
var fSource = DriveApp.getFolderById('xxxxxxxxxxxxx'); // folder where files are saved
var file = DriveApp.getFilesByName("content.csv").next(); // currently searching by file name
var csvData = Utilities.parseCsv(file.getBlob().getDataAsString()); csvData.splice(299,csvData.length-300);
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
You can order the files by date so you can list the recently uploaded files, and when you hit an already downloaded file you just stop whole process.
https://developers.google.com/drive/api/v3/reference/files/list#orderBy
Try this:
function getLatest(){
var optionalArgs = {
orderBy:"modifiedDate",
q:"title='TITLE'"
};
var files = Drive.Files.list(optionalArgs).items;
Logger.log(files);
}
This will use the Advanced Services API to search for the files and order them by date. To use this code you'll need to enable Google Advanced Services, which allows you to use the APIs directly. You should also look at the File Resource to know what properties are available. Lastly, files holds an array of the files returned by the list.
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.
I have a script which creates a file in a shared Google Drive folder, this is the script:
var spr = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Klantenlijst');
var data = spr.getDataRange().getValues();
var klanNumbers = data; //some var declared before this piece of code
var file = DriveApp.createFile(fileName, JSON.stringify(klanNumbers));
This file needs to be updated frequently, to do so I remove the existing file and create a new one to replace it (with the new data). The problem is that when I try to perform the setTrashed action as a user other than the file owner, this error pops up:
You do not have authorization to perform that action.
Any ideas on how to fix that? :)
Thanks!
EDIT: I can delete the file in drive manually with the other users.
I have seen this article but I totally disagree with the conclusion that the problem is "too localized". Look around on Google and you will find cases with the same problem without a decent solution.
Workaround for this moment:
Rename the file
Move it to another folder
Create the new file in the old folder
I will not delete this post so people can add other ideas here.
You can only trash files that you own. When you delete the file manually (using the GUI to trash the file), it appears that you've trashed the file, but you are not actually setting the trashed flag on it. Rather, you are removing it from view in your own Google Drive, without affecting anyone else. The owner still sees it shared with you, and any other collaborators are unaffected. In fact, you can still see the file if you search for it by its full name, or use one of the alternate views such as the "Recent" file list, or use the file's URL.
To get the same effect from a script, use removeFile().
Here's a utility that will treat a file differently for owners than collaborators, to either trash or remove it.
/**
* Remove the given file from view in the user's Drive.
* If the user is the owner of the file, it will be trashed,
* otherwise it will be removed from all of the users' folders
* and their root. Refer to the comments on the removeFile()
* method:
*
* https://developers.google.com/apps-script/reference/drive/drive-app#removeFile(File)
*
* #param {File} file File object to be trashed or removed.
*/
function deleteOrRemove( file ) {
var myAccess = file.getAccess(Session.getActiveUser());
if (myAccess == DriveApp.Permission.OWNER) {
// If I own the file, trash it.
file.setTrashed(true);
}
else {
// If I don't own the file, remove it.
var parents = file.getParents();
while (parents.hasNext()) {
// Remove the file from the current folder.
parents.next().removeFile(file);
}
// Remove the given file from the root of the user's Drive.
DriveApp.removeFile(file);
}
}
Example:
function test_deleteOrRemove() {
var files = DriveApp.getFilesByName('536998589.mp3');
while (files.hasNext()) {
var file = files.next();
deleteOrRemove( file );
}
}