google apps script. copy files to one drive - google-apps-script

I would have files stored in google drive and I would like to copy (or move) those files to my OneDrive. I have managed to connect OneDrive to google drive and I can successfully create folders and upload files by file ID. I am trying to copy (or move) multiple files at once from google drive to OneDrive though without any luck yet. I am not good at programming just doing everything by tutorials only but yet could not find any working one. Maybe anyone could guide me how to do it? For the final idea I would like to achieve that files from google drive would be copied even to separate folders by the part of file title (name and surname, if to be exact). Currently I have "developed" such script:
function moveFiles(source, dest_folder) {
var source = DriveApp.getFolderById("1faFbaXJNziwIGyer2H2IPALQ8ahBfGMc");
var prop = PropertiesService.getScriptProperties();
var odapp = OnedriveApp.init(prop);
var files = DriveApp.getFiles();
while (files.hasNext()) {
var file = files.next();
var dest_folder =
OnedriveApp.init(PropertiesService.getScriptProperties()).uploadFile(files,
"/samplefolder");
}
}

I believe your current situation and your goal are as follows.
You are using OnedriveApp.
You have already been finished the authorization process. So you have already been had the access token and refresh token in the PropertiesServices.
You want to upload the files in a specific folder of Google Drive to a specific folder in OneDrive.
The number of files is 10 - 20.
The file size is small.
From your following reply
I have changed accordingly to: var files = file.getId(); but then I receive such error: TypeError: Cannot read property 'getId' of undefined moveFiles # srcpt.gs:5 If I use DriveApp.getFiles() or source.getFiles(), I receive such error: Exception: Unexpected error while getting the method or property getFileById on object DriveApp. convToMicrosoft # code.gs:629 OnedriveApp.uploadFile # code.gs:460 Appreciated for any help.
About var files = file.getId(); and If I use DriveApp.getFiles() or source.getFiles(), I receive such error:, unfortunately, I cannot understand it.
In this case, how about the following modification?
Modified script:
function myFunction() {
var prop = PropertiesService.getScriptProperties();
var odapp = OnedriveApp.init(prop);
var source = DriveApp.getFolderById("###"); // Please put your folder ID.
var files = source.getFiles();
while (files.hasNext()) {
var file = files.next();
odapp.uploadFile(file.getId(), "/samplefolder/"); // Please set the destination folder name. In this case, the folder name in OneDrive.
}
}
When "/samplefolder" is used, an error occurs. Please enclose the folder name by / like "/samplefolder/". Please be careful about this.
When this script is run, the files in the specific folder of Google Drive are copied to the destination folder of /samplefolder/ in OneDrive.
References:
OnedriveApp
getFolderById(id)
getFiles()

Related

Google apps script to clear folder given a folder_id not working (isTrashed not deleting files)

I am trying to write a google apps script to clear a given folder given the folder ID but the function is not behaving as expected. It runs without an error but it seems isTrashed() does not delete all files? I have looked at the documentation but can't seem to figure out how to get all the files in a folder to be deleted.
function clearFolder(folderId) {
// Get the folder
var folder = DriveApp.getFolderById(folderId);
Logger.log("clearFolder on folder: %s",folder.getName())
// Get all the files in the folder
var files = folder.getFiles();
// Iterate through the files and delete them
while (files.hasNext()) {
var file = files.next();
Logger.log("clearFolder deleting file named '%s'",file.getName())
file.isTrashed();
}
}
The file.isTrashed() method does not delete files. It determines whether the file is in the trash, and returns a true/false value that is ignored by the code you quote.
To delete files, use file.setTrashed(true).

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
}
}

Trying to duplicate a file without knowing its ID or name

I am trying to figure out a way to check whether or not a set of folders I'm looping through has a file (google docs file) in it. If it does have a file in the folder (there's ever only one file) I would like to make a copy of it.
I'm not sure how to access that file and use the makeCopy() method since I don't know the name / ID of the file in the folder.
Any help would be very appreciated.
How about following sample script? THis sample retrieves files in the folderId. If there is a file in the folder, the file is copied. From your question, it is found that there is only one file in the folder. So in this script, the one file is copied.
Sample script :
var folderId = "### folder ID ###";
var folder = DriveApp.getFolderById(folderId);
var files = folder.getFiles();
var file = [];
while (files.hasNext()) {
file.push(files.next());
}
if (file.length > 0){
file[0].makeCopy();
}
Other sample script :
Since the file which is copied is only one, follwing sample script can be also used for your situation. This may be more simple than above.
var folderId = "### folder ID ###";
var files = DriveApp.getFolderById(folderId).getFiles();
files.hasNext() && files.next().makeCopy();
If you want to use folder name and the folder name is only one in your Drive, please use following script.
var folderName = "### folder name ###";
var files = DriveApp.getFoldersByName(folderName).next().getFiles();
files.hasNext() && files.next().makeCopy();
You have the ID of the folders (or at least you have their names so you can get their IDs using files.list?q=name="foo"
Once you have the folder IDs, you can look for any files therein using files.list?q="folderID" in parents

Google apps script: How to create a downloadable html file?

Starting with 'google apps script'. I've created a simple script that logs some information with 'Logger.log("message");' with this lines being in a loop, so the log message is quite large.
I'd like now to create an html file with that same information and either being able to download that file locally or have it downloaded to my google drive.
Any idea how that could be achieved? I've tried looking examples for a while but I cannot have anything working...
Many thanks!
Yes you can, you should read first. Have a look this documentation
function createMyHTMLlog()
{
var folders = DriveApp.getFoldersByName('ff');// ff:your folder name on drive
if (folders.hasNext())
{
var folder = folders.next(); //select the folder
folder.createFile('Log','<b> your message here </b>', MimeType.HTML); //create the file
}
}
Update: Add more content later
function logUpdate()
{
var children = folder.getFilesByName('Log');// log is the created file name
if (children.hasNext())
{
var file = children.next();
var logContent = file.getAs('text/plain').getDataAsString();// get available msg
logContent = logContent.concat('<br>your<b> updated message </b> here'); // combine with new msg
file.setContent(logContent);
}
}

Downloading multiple files from google addon

Hi I'm trying to download multiple files from a google folder as txt. I'm using the google script. So far my code will successfully download the first file from a folder but it stops and wont download the rest of the files in that folder. Thanks
function doGet() {
var folder = DriveApp.getFolderById('FolderKeyHere')
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
var id = file.getId();
var doc = DocumentApp.openById(id);
var string = doc.getBody().getText();
var output = ContentService.createTextOutput();
output.setMimeType(ContentService.MimeType.TEXT);
output.setContent(string);
output.downloadAsFile(file.getName());
return output;
};
};
This won't be possible like that, the return output; will actually "return" the app and of course exit the while loop.
I think you won't be able to loop this kind of process without user action.
You might build a small Ui that would have a button to download files one by one on each button click but I guess that's not what you are looking for.
Why not create all the files in your drive, compress all the files in a single zip file, download the zip and then delete the files and the zip from your drive ?
Slightly longer to write but -I think - the only useable workflow to get multiple files in a single download.