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.
Related
Hi I've got this Google App script that needs to overwrite a file.
At the moment it creates a copy.
Is there a line or two that can check if it exists,then delete?
Or is there an alternative to createFile that overwrites?
DriveApp.getFolderById(fold).createFile(file.getName()+'-'+sheet+'.csv', csv);
Many thanks for looking!
Filenames are not unique on Google Drive - the uniqueness of files is determined by their ID. Whereas on a regular file system, creating a file with a similar filename would erase the old file, in this case you are creating a new unique file every time.
As far as I know, the easiest way would the be to move the existing file to the trash. You can keep you existing script but add to it. Assuming your file will always exist, this should work:
const folder = DriveApp.getFolderById(fold);
folder.getFilesByName(file.getName()+'-'+sheet+'.csv').next().setTrashed(true);
folder.createFile(file.getName()+'-'+sheet+'.csv', csv);
If you are unsure that a file with that name will exist, or if there might be multiple files with that name, you will have to iterate through all them:
const folder = DriveApp.getFolderById(fold);
const files = folder.getFilesByName(file.getName()+'-'+sheet+'.csv');
while(files.hasNext()){
let f = files.next();
f.setTrashed(true);
}
folder.createFile(file.getName()+'-'+sheet+'.csv', csv);
I haven't tested this code, but it should be pretty close to what you need.
Edit
Contrary to what I said, the method DriveApp.File.setContent(content) can overwrite the content of a file. The above solution still works and avoids potential data loss.
I'm trying to create a copy of a document and populate it with data from a spreadsheet. I can successfully create the copy but the script can't seem to access it to edit its contents. Here's the code:
var file = DriveApp.getFileById('1mWFhZpZVJpYJleg9n5qq3tr7EHwUIlbM');
var copy = file.makeCopy('SKPembimbing_' + nim, folder).getId();
var doc = DocumentApp.openById(copy);
var body = doc.getBody();
It always gives me an error at the 3rd line when it tries to open the document for editing.
(Exception: Document is inaccessible. Please try again later.)
I saw another thread from last year with the same exact question but without a solution. I've been working all night trying to get this darn thing to work. Does it have to do with my scope? I'm running it on a trigger on edit.
I found the solution:
The template document I was copying was a .docx file, NOT a Google Doc. The copied file was thus also a .docx file so was inaccessible from the DocumentApp. All I had to do was convert it to a Google Document.
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){};
}
Im using the script editor in a Google spreadsheet, and I want to create a folder inside a root folder , already created. I've tried to follow the official notice of the API DriveApp, but without success.
Here is my code :
function createSubFolder(rootFolder,name){
DriveApp.getFoldersByName(rootFolder);
DriveApp.createFolder(name);
}
I've tried also ( following this old post working with the old version of DriveApp : i.e DocsList) :
function createSubFolder(rootFolder,name){
DriveApp.getFoldersByName(rootFolder).createFolder(name);
}
It seems to be very easy but I don't see where am I wrong.
Does anyone know the way to do it?
Thanks
You need to assign values to a variable.
function createSubFolder(rootFolder,name) {
var AllFoldersWithThisName = DriveApp.getFoldersByName(rootFolder);
var theFirstFolderWithThisName = AllFoldersWithThisName.next();
theFirstFolderWithThisName.createFolder(name);
};
In Google Drive, you could have 1,000 folders all with the same name. Same thing with file names.
The getFoldersByName() method returns:
FolderIterator — a collection of all folders in the user's Drive that have the given name
You need to get one of the folders out of the collection of folders. That is done with the next() method.
New to Google Apps script here, but have some coding experience. I want to scan current folder for spreadsheets. For each spreadsheet found, I want to change the value in a specific cell (say cell F16 in "Sheet1") to "Q1 FY16". Here is what I have so far:
function myFunction() {
var folderID ="0BxfGszImm3D9flpVlWXd4bjQ";
var topFolder = DriveApp.getFolderById(folderID);
Logger.log(topFolder.getName());
var filesList = topFolder.getFiles();
while (filesList.hasNext()) {
var file = filesList.next();
Logger.log(file.getName());
file.getSheetByName("Sheet1").getRange("F16").setValue("Q1 FY16");
}
}
There are two main problems:
I have to specify a folder ID in this and I don't want to. I want the code to run in the current directory (and eventually I will make it recursive to scan all subfolders as well).
The File class doesn't have the "getSheetByName()" or "getRange()" methods, but I don't know how to cast the files into Spreadsheets.
Any help with this would be greatly appreciated.
Cheers
Where will you be launching this script from? They are no way of launching script directly from google drive.
to Be able to use the getSheetByName() and the getRange() you need to open the file as a spreadsheet.
instead of using this line:
file.getSheetByName("Sheet1").getRange("F16").setValue("Q1 FY16");
You should use something like this :
try {
SpreadsheetApp.openById(file.getId()).getSheetByName("Sheet1").getRange("F16").setValue("Q1 FY16");
}
catch(e){}
you need to use the try - catch since some of the files won't be spreadsheet and give and error when trying to use the SpreadsheetApp.openById().
I hope this helps you a bit, I'll try to update this answer once I get more information for the first part.
Best of luck.