Deleting files from Google Drive with Google Apps Script [duplicate] - google-apps-script

This question already has an answer here:
Permanently delete file from google drive
(1 answer)
Closed 4 years ago.
I have seen many topics talking about this problem, and I have been struggling with it for a week now: is there a real way to delete/remove/put to trash files from Google Drive using a script?
I have to upload CSV files on Drive to copy some of their rows into a Spreadsheet, and I would like to have these files deleted after use. I used DriveApp.remove(file.id), Drive.Files.remove(file.id) and, even though they did nothing on my documents, I did not get any error message...
I can use a method taking filenames, fileIDs in argument, whatever is needed to perform this deletion.

Per Apps Script documentation, the .removeFile(fileId) method does not delete the file, nor does it trash the file. This method simply removes the file from the current folder.
To delete a file from Google Drive via Apps Script will require using the Drive REST API possibly as an advanced service. This will skip the "Trash" - it is unrecoverable.
function deleteIt(fileId) {
var file = Drive.Files.get(fileId);
if(file.mimeType === MimeType.FOLDER) {
// possibly ask for confirmation before deleting this folder
}
Drive.Files.remove(file.id); // "remove" in Apps Script client library, "delete" elsewhere
}
"Trash"ing a file/folder can be done from Google Apps Script without needing to set up and configure the advanced service:
function trashIt(fileId) {
var file;
try {
file = DriveApp.getFileById(fileId);
}
catch (fileE) {
try {
file = DriveApp.getFolderById(fileId);
}
catch (folderE) {
throw folderE;
}
}
file.setTrashed(true);
}
(Trashing can also be done with the Advanced Service if you need to work with Team Drive items.)
See related questions:
Permanently delete file from google drive
Delete or Trash specific file in Drive
Google apps script : How to Delete a File in Google Drive?

Related

Automatic Syncing between two Google Drive Shared Drives

Question:
I have two Google Shared Drives (Team Drives), let's say Movies and MoviesBackup. I need to backup whatever I upload to Movies into MoviesBackup. For this, I need an unidirectional sync from Movies to MoviesBackup, once daily.
What I have tried:
I know of of Rclone, and have used its Command Line Interface to sync between two Shared Drives. Maybe if Rclone can be used from Google AppScript, I would set a daily trigger. But I seem to find no way to do so.
Any other solutions that work will be appreciated.
Although I'm not sure whether this is the direct solution of your issue, in your situation, how about the following sample script? This sample scripts uses a Google Apps Script library. Ref
When this library is used, a source folder can be copied to the specific destination folder. And, when the files in the source folder are updated, the updated files are copied to the destination folder as the overwrite.
Usage:
1. Install library.
Please install the library to your Google Apps Script project. The method of installing it can be seen at here.
2. Sample script.
Please copy and paste the following script to the script editor of your Google Apps Script project. And save it. And, in this library, Drive API is used. So please enable Drive API at Advanced Google services.
And, please set the source and destination folder IDs to the following object.
function myFunction() {
const object = {
sourceFolderId: "###", // Please set the source folder ID.
destinationFolderId: "###", // Please set the destination folder ID.
overwrite: true,
};
const res = CopyFolder.copyAllFilesFolders(object);
console.log(res);
}
Note:
When this script is run for the 1st time, all files are copied. And, after the script is run as 2 times, only the updated files are copied.
Reference:
CopyFolder of Google Apps Script library

How can I automate OAuth requests in Google Sheets when cloning file? [duplicate]

I've set up a script that essentially copies the contents from a 'template' folder within my google drive and moves the copied contents to a newly created folder elsewhere. The 'Template' folder will always hold 9 individual spreadsheets, each with their own unique bounded script.
The problem I'm having is that every time I copy the spreadsheets over, I have to reauthorise access for each of the 9 scripts before I can start using the functionality I've created.
I'd like to be able to assign or grant permission for the bound script to access the services it needs to during the process I use to copy the spreadsheet to a new location.
Here is an example of the code I use to copy over the spreadsheets. Is there anyway to access the script to assign permissions here?
function copyContents(template_folder, new_folder){
var files = template_folder.getFiles();
while (files.hasNext()) {
var file = files.next();
var file_name = file.getName()
var copied_file = file.makeCopy(file_name,new_folder)
// Assign permissions here...
}
}
It's not possible to grant authorization programmatically as this implies a security risk. The alternative is to publish your bounded scripts as add-ons so you authorize them once and you will be able to use them on any spreadsheet.
Bear in mind that you still should have to enable the addons on each of the documents you want to use them but this usually as simple as having a an onOpen menu that runs with ScriptApp.authMode.NONE
Note: I'm pretty sure that this was already asked and answered on this site.
Similar questions without answers with positive score
Installable onEdit trigger in google spreadsheet script when copying a template spreadsheet script
Google Script Carrying over triggers when copying a spreadsheet

Check if google document is neither edited nor viewed

Does google app script offers a class with a method allowing to check if a document with a given id is edited or viewed.
I'm build an application that allows user to delete google document from the google disk but before moving file to trash I would like to check if the file is neither edited nor viewed.
The similiar question has been posted here, but no solution provided.
Getting a list of active file viewers with apps script
Please note the the lock service is not a solution to this problem.
The Google Drive API must be used to get revisions to a file. The built-in DriveApp service, which is different than the Advanced Drive service, has no capability to get file revisions information, except for getLastUpdated() method, which gets the date when the file was last updated. The Drive API can be used within Apps Script by using the Advanced Drive service.
Advanced Services within Apps Script must be enabled. Click the "Resources" menu, and then choose the Advanced Google services menu item.
After you have enabled the Advanced Drive Service, the "Drive" class will show up in the context menu. Use Ctrl + Space Bar to have a list of available classes displayed in the code editor.
To get revisions to a specific file, use the Revisions class of the Advanced Drive service.
Drive.Revisions.list(fileId)
Check for no revisions:
function trash_If_No_Changes_(fileID) {
var revs;
revs = Drive.Revisions.list(fileID);
if (revs.items && revs.items.length === 0) {
trashFile_(fileID);
}
}
The Advanced Drive Service can also delete a file without sending it to the trash first.
function trashFile_(fileID) {
var i;
/*
This deletes a file without sending it to the trash
*/
for (i=1;i<4;i++) {
try{
Drive.Files.remove(fileID);//deletes a file without sending it to the trash
return;//return here instead of break because if this is successful the task is completed
} catch(e) {
if (i!==3) {Utilities.sleep(i*1500);}
if (i>=3) {
errHndl_(e,'trashFile','Can not delete the file by ID');
return false;
}
};
}
}
If you want to avoid the need to ask the user for broad access to their Drive, then you may want to try setting the scope:
https://www.googleapis.com/auth/drive.file
In the appsscript.json manifest file.

How can I check that my GoogleSpreadsheet is in my drive or in a teamdrive?

Like I said on the title, I would like to run a Google apps script linked to a google spreadsheet only if the Spreadsheet is located on the user's drive because I work with Spreadsheet template located on teamdrive and the rule is that the user must make a copy on their local Drive to run the script. So I would like to know if it's possible with the file id for exemple to check if I am in a teamdrive or not ?
Thanks for your answers
With the fileId itself, you cannot know whether it is part of a shared drive or not.
However, you can use DriveApp to obtain the file itself, and most importantly, its permission. In order to check that the file is in a personal drive (and owned by the user issuing the request), you have to make sure the permission is in fact OWNER. You can do this with GAS as follows:
function isInPersonalDrive(fileId) {
var file = DriveApp.getFileById(fileId);
return file.getAccess(Session.getActiveUser()) === DriveApp.Permission.OWNER;
}

Google App Scripts Remove ALL Files in Drive

Good morning, I am running into some issues when creating a google app scripts to remove all files/folders from the root of the Google Drive. I have found the following code but it appears to error out when running;
function deleteFile(idToDLET) {
idToDLET = 'the File ID';
//This deletes a file without needing to move it to the trash
var rtrnFromDLET = Drive.Files.remove(idToDLET);
}
Error Code = Script function not found; myFunction
Thanks
Thanks to #CTOverton answer, I've created another version as I noticed that a File has the setTrashed method, which moves the file in the trash bin.
If the Drive has important files saved, I'd suggest to move files to trash instead of doing a permanent deletion, it may save you from a disaster while doing scripting experiments :-)
This version uses a folder id which you can get with: folder.getId().
You can use CTOverton's code to delete all files on your Drive (commented).
function emptyFolder(folderId) {
const folder = DriveApp.getFolderById(folderId);
while (folder.getFiles().hasNext()) {
const file = folder.getFiles().next();
Logger.log('Moving file to trash: ', file);
file.setTrashed(true);
// Delete File
//Drive.Files.remove(file.getId())
}
}
Cheers
As #James D said, you are missing the myFunction which is the default function in order to run the script. Make sure to save your script first.
Here is the code to get all the files and delete them.
function myFunction() {
// Get all files in Drive
var files = DriveApp.getFiles();
// Delete every file
while (files.hasNext()) {
var file = files.next();
Logger.log('Deleting file "%s"',
file.getName());
// Delete File
Drive.Files.remove(file.getId())
}
}
In order to use DriveAPI, you need to add it through the Resources>Advanced Google Services menu. Set the Drive API to ON. AND make sure that the Drive API is turned on in your Google Developers Console. If it's not turned on in BOTH places, it won't be available.
WARNING
Apps scripts are stored as files in Google Drive...
This script upon running will remove any and all files in the connected google drive account, including itself.
Hope this helps!