I can file.addToFolder but cant file.removeFromFolder - google-apps-script

I have a script that reads files from a folder and catalogs the contents to a spreadsheet. To avoid duplicates I want to move the files to a different folder (file.addToFolder(newFolder)) which works, however when I try to file.removeFromFolder(formerFolder) I get "cannot find method" which would suggest I am not giving it the right class of object even though removeFromFolder is listed as a member of the File class.
function moveFileToFolder(fileId, targetFolderId,formerFolderId) {
var targetFolder = DocsList.getFolderById(targetFolderId);
var file = DocsList.getFileById(fileId);
file.addToFolder(targetFolder);
file.removeFromFolder(formerFolderId);
};
What am I doing wrong?

You should get the formerFolder like you get the targetfolder and pass it to the method instead of the formerFolderId.

Related

Google Apps Script moving file to Team Drive folder

Background:
At the core of the issue is I have an Alteryx job dropping files into my google drive. These files need, in actuality, in a Team Drive folder. Try as I might, nowhere have I found a way for Alteryx to do this. So hence the need for this script.
Actual problem:
So here is the criteria: I have the files being created with the same naming convention with only the date changing. I need these files to go from my drive to a team drive where they are eventually worked on.
Using the resources already here on stack I found wonderful solutions here: 1 and here 2 that I was able to cobble together a working script.
Understand I am a marginally functional python programmer for data analytics. So my JS and Google scripting are rudimentary at best. The first time I tested the script, it worked. Wonderfully, right up until it didn't.
It moved my first file with no problem. I then created a few copies of that same file in the drive to see how it handled multiple. I now get an error:
Exception: No item with the given ID could be found, or you do not
have permission to access it. (line 15, file "CodeA1")
Here is my code:
function SearchFiles() {
//searches based on naming criteria
var searchFor ='title contains "Reference Data Performance"'; //test file
var names =[];
var fileIds=[];
var files = DriveApp.searchFiles(searchFor);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
fileIds.push(fileId);
var name = file.getName();
names.push(name);
}
var file = DriveApp.getFileById(fileIds);
supportsTeamDrives: true;
supportTeamDrives: true;
var targetFolder = DriveApp.getFolderById('TEAMDriveID');
targetFolder.addFile(file);
}
Exception: No item with the given ID could be found, or you do not
have permission to access it.
This error occurs most often if either
The TeamDriveId is not correct
The account from which you run the script is not member of the team drive
Also note:
supportsTeamDrives: true;
supportTeamDrives: true;
are parameters
for the Drive API, not to be confused with DriveApp
Update:
I ended up going with a simplified version of this script. I had Alteryx schedule the file creation (three different files) at hour increments. Then made a trigger in Google Apps to run the script at the times directly after each Alteryx scheduled drop. Simple? Yes. Inelegant? Maybe. Been running all week and files arrive at their destination for people to work on.
function SearchFiles() {
//searches based on naming criteria
var searchFor ='title contains "Reference Data Performance"'; //looks for file that matches requirements
var files = DriveApp.searchFiles(searchFor);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
var file = DriveApp.getFileById(fileId); //grabs file ready to pass to google drive.
supportsTeamDrives: true;
supportTeamDrives: true;
var targetFolder = DriveApp.getFolderById('FOLDERID');
targetFolder.addFile(file);//good for getting a single file needs loop to grab multiple from Array
}
}

How to open a spreadsheet only by name of the corresponding file in Google Sheets?

I need a way to open a spreadsheet only by having the name of the corresponding file and the folder where the file is located. What I'm trying to do is creating a temporary copy of an active spreadsheet and reading information from the copy file rather than the active one. But unfortunately this copy file won't have a constant ID and URL as it's going to be erased every time after the script is done, and re-created with the next running of the script.
What I already tried is using the URL of the temporary file in order to open the spreadsheet itself, as you can see below.
But it's not useful for me, as I don't have a constant URL of this file (as it will be erased in the end of the script and have a new URL with the next script). But I have a constant name of the file, as well as this will be the only file in the respective folder.
What I also tried is looking for methods to open file only using its name (which is "temp_copy" in a 'temp_folder'). But I didn't find a working solution.
var report = SpreadsheetApp.getActiveSpreadsheet();
var temp_folder =
DriveApp.getFolderById("1EAsvVcFjIw5iGTeF_SxxQJLVlaLHl_pR");
DriveApp.getFileById(report.getId()).makeCopy("temp_copy", temp_folder);
var temp_copy = SpreadsheetApp.openByUrl(' ');
var hiddenSheet = temp_copy.getSheetByName('DATE');
var lastRow = hiddenSheet.getSheetValues(1,1,1,1);
var sheet = temp_copy.getSheetByName('forCSV');
var lastColumn = sheet.getLastColumn();
var activeRange = sheet.getRange(1,2,lastRow,lastColumn);
What I'm expecting as a result is to make the link between the 3rd line of the code (when making a copy of the basic file) and 5th line of the code onwards (when referencing specific range from the temporary file) only by using name of the file or respective folder. In theory it seems so easy, I should be missing something somewhere...
Many thanks in advance!
You can use DriveApp to get a FileIterator which contains the Sheet.
var file, files = DriveApp.getFilesByName("temp_copy");
if (files.hasNext ()){
file = files.next(); // Get first result for name
} else {
return "";
}
var sheet = SpreadsheetApp.openById(file.getId())

How to get a document object from a file object in a Google-Apps Script

My problem is that I have a number of Google documents (docs) and each has a table of contents. I want to grab the TOC's and place them in another document. This should be easy, but I have run into a snag.
I can grab all of files in a folder with:
var folder = DocsList.getFolder('yourfolder');
var contents = folder.getFilesByType(DocsList.FileType.DOCUMENT);
This gives me an array of files as the variable 'contents'
Great.
I also know that
var TOC = **doc**.getAs(DocumentApp.ElementType.TABLE_OF_CONTENTS)
The problem is that I cannot figure out how to get a document object from a file object or alternately how to get an array of documents in a folder rather than an array of files.
I have searched for an answer and not only on this site. If anyone can help, I would appreciate it very much
DocsList and DocumentApp have at least one method in common which is that they have access to the ID of documents so it is quite straightforward to pass this ID parameter from one method to the other.
This code demonstrates :
function myFunction() {
var folder = DocsList.getFolder('yourfolder');
var contents = folder.getFilesByType(DocsList.FileType.DOCUMENT);
var docObject = [];
for(var c in contents){
docObject.push(DocumentApp.openById(contents[c].getId()));
}
Logger.log(docObject);// now you have an array of DocumentApp objects
}

How to delete/overwrite CSV file using google apps script?

My google apps script imports a csv file [test.csv] into a new tab, manipulates some values, then saves the manipulated tab as a csv file [test.csv]. When it saves the new version, it simply makes another copy [test(1).csv]. I wish instead to overwrite the previous file (or delete the old one then export/write the new version.) Help please?
I am using reference code from the Interacting With Docs List Tutorial
I know this is an old question, but much of the information in the accepted answer has been deprecated by Google since then. DocsList is gone, as are the clear() and append() methods on a file object.
I use the following function to create or overwrite a file:
// Creates or replaces an existing file
function updateFile (folder, filename, data) {
try {
// filename is unique, so we can get first element of iterator
var file = folder.getFilesByName(filename).next()
file.setContent(data)
} catch(e) {
folder.createFile(filename, data)
}
}
For reference, here's some code for doing the same for a folder. It assumes we're operating in the parent folder of the current sheet and want a folder
object for a new or existing folder there.
// Get folder under current folder. Create it if it does not exist
function getOrCreateFolder(csvFolderName) {
var thisFileId = SpreadsheetApp.getActive().getId();
var thisFile = DriveApp.getFileById(thisFileId);
var parentFolder = thisFile.getParents().next();
try {
// csvFolderName is unique, so we can get first element of iterator
var folder = parentFolder.getFoldersByName(csvFolderName).next();
// asking for the folder's name ensures we get an error if the
// folder doesn't exist. I've found I don't necessarily catch
// an error from getFoldersByName if csvFolderName doesn't exist.
fname = folder.getName()
} catch(e) {
var folder = parentFolder.createFolder(csvFolderName);
}
return folder
}
You could do DocsList.find(fileName) which gives you a list of files that have that name. If file names are unique, then you can just do var file = DocsList.find(fileName)[0].
If you are a Google Apps user, you can use file.clear() to remove all the contents of the old file, and then file.append() to insert all of the new contents.
Otherwise, you will have to file.setTrashed(true) and then DocsList.createFile() to make the new one.

google script: File class is not defined

I'm trying to make my google docs script create a backup copy of the file each time I open it.
To make a copy I write
var name = File.getName();
var filecopy = File.makeCopy(name + " backup");
But it won't recognize the File class. Although it knows DocsList. How do I make it work or make a copy of the file another way?
GAS permits to call class methods or instance only native classes (Object, String, etc), own classes or Google Services (DocList, SpreadsheetApp, etc). Other classes like File, Folder, Spreadsheet, Range, etc are accessible and instanceable only via calling the services functions, for example, DocsList.getFileById("..."); returns the File class instance.
The following function copies a file having the srcFileID ID to a new file with the name stored in the dstFileName parameter.
function testCopy(srcFileID, dstFileName) {
var srcFile = DocsList.getFileById(srcFileID);
srcFile.makeCopy(dstFileName);
}
You cannot use the File class that way. Use something on these lines
var file = DocsList.getFileById(ID) ; // you can use DocsList.find or DocsList.create
var filecopy = file.makeCopy();