Google App Scripts Remove ALL Files in Drive - google-apps-script

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!

Related

Apps Script - Search Gmail label for all attachments and overwrite files to google drive folder

Using prior articles and questions found within stack overflow I was able to find a snippet of App Script that searches Gmail labels for attachments and moves them to a specific folder in Google Drive.
function saveAttachmentInFolder(){
var folder = DriveApp.getFolderById('xxosi2');
var userId = "please.thanks#gmail.com";
var query = "label:thankyoucards-reports";
var res = Gmail.Users.Messages.list(userId, {q: query});//I assumed that this works
res.messages.forEach(function(m){
var attA=GmailApp.getMessageById(m.id).getAttachments();
attA.forEach(function(a){
folder.createFile(a.copyBlob()).setName(a.getName());
});
});
}
I need to modify this code to perform the following additional functions:
If file exists, overwrite and retain version history
I have also played around with the answer found in the following thread to no avail as I believe this is hard coded in some way and too specific to the one file type (xlsx) Copying attachments from Gmail to Google Drive folder and overwriting old files with Apps Script.
I believe your goal is as follows.
You want to check this using the filename between the existing file in the folder and the attachment file.
You want to overwrite the existing file with the attachment file.
In this case, how about the following modification? In this case, Drive API is used. So, please enable Drive API at Advanced Google services.
From:
folder.createFile(a.copyBlob()).setName(a.getName());
To:
var filename = a.getName();
var files = folder.getFilesByName(filename);
if (files.hasNext()) {
Drive.Files.update({}, files.next().getId(), a.copyBlob(), {supportsAllDrives: true});
} else {
folder.createFile(a.copyBlob()).setName(filename);
}
When this modified script is run, the existing file is searched from the folder using the filename of the attachment file. When the file is found, the file is overwritten by the attachment file. When the file is not found, the file is created as a new file.
Note:
In this modified script, the existing file is overwritten. So, please be careful about this. I would like to recommend using a sample file for testing the script.
Reference:
Files: update of Drive API v2

How do I delete a specific type of file (CSV files) within a specific folder with google app script on a shared google drive folder

I am having trouble adding files to the shared google drive folder as well as not being able to remove specific types of files of any kind within my script. The shared google drive file gives me issues. The code below works for me on my own personal google drive folder for adding and removing CSV's from one google drive folder to any another that I specify. However, it does not work with our general shared google drive folder. I have been authorized permission via the google cloud console API for Drive & Sheets but I am still having permission issues. Any help or clarification on this issue would be greatly appreciated.
Here are two different pieces of code. The first one with function moveFiles() works on my personal drive but not in the shared folders. Here is also some more code that I was playing around with to test the shared folders in a simpler manner. I was able to get the putFile() function to put a newDoc inside a shared google drive folder but not able to remove it.
function moveFiles(source_folder, dest_folder)
{
// set current destination to grab the folder from
var currentFolder=DriveApp.getFolderById("1emSsRay_WI_z_qBUpQIoccxQID28FvB0");
// grab only the csv's within current folder
var docs = DriveApp.getFilesByType(MimeType.CSV);
// set target destination where we will store old csv's that have been processed & Analyzed
var destination = DriveApp.getFolderById("1wYG1Gd5z0-nucedSMOBn8ZJs68ZgR8Hb");
// iterate through the csv's files within the currentFolder, add them to the destination and remove them from the current folder
while (docs.hasNext())
{
var doc = docs.next();
destination.addFile(doc); // get error "Cannot use this operation on a shared drive item(line 13, file "SharedDriveMove")
currentFolder.removeFile(doc);
}
}
function putFile()
{
var newDoc = DocumentApp.create('Testing Team Drive MoveTo').getId();
var file = DriveApp.getFileById(newDoc);
var moveFile = DriveApp.getFolderById('1emSsRay_WI_z_qBUpQIoccxQID28FvB0').addFile(file);
}
function takeFile()
{
var filesIterator = DriveApp.getFilesByName('Testing Team Drive MoveTo');
while (filesIterator.hasNext())
{
var file = filesIterator.next();
}
var cleanup = DriveApp.getFolderById('1wYG1Gd5z0-nucedSMOBn8ZJs68ZgR8Hb').addFile(file,{"supportsAllDrives": true}); // get error "Cannot find method addFile(File,Object).(line 15,file"Code")
var moveFile = DriveApp.getFolderById('1emSsRay_WI_z_qBUpQIoccxQID28FvB0').removeFile(file,{"supportsAllDrives": true});
}
DriveApp is an Apps Script class whereby it has it's limitations among Drive. Also, as the documentation says:
This method does not delete the file, but if a file is removed from
all of its parents, it cannot be seen in Drive except by searching for
it or using the "All items" view.
You should do it with the Drive API instead:
Use "supportsAllDrives", otherwise it won't find the file if it's in a Shared Drive (until this is deprecated in 2020).
Drive.Files.remove("your file ID", {"supportsAllDrives": true});
You also have to authorize the Drive.File scope.

Google Drive Service. Copied file to group drive folder. File is blank

I'm having an issue with the file handling of a Google Sheet that is produced from another Google Sheet when I run a google apps script. When I run the script, a new output file is produced and sent to folders with a specific label. The goal is to have the output file added to a specific folder in a group drive. The script and files regarding my problem all reside on the group drive too fyi.
When I run the script this is what happens.
A file is created within my personal Google Drive because I have a folder with the same exact name as the one on the group drive (this was my test environment for the script). This file on my drive has all the desired output within the Google Sheet. A file was also being added to the root of my drive, but the script now removes it from the root.
A file is created on the group drive, but it is completely empty. The file is correctly named, but there are no contents within the actual spreadsheet.
Here is the script that is handling the output file:
var sourceFilename = ss.getName();
var splitSourceFilename = sourceFilename.split("LMS");
var targetFilename = splitSourceFilename[0] + "Allowed_Layers_Vx";
// move the new spreadsheet to Allowed Layers Lists folder
var folders = DriveApp.getFoldersByName("Allowed Layers Lists");
while (folders.hasNext()) {
var folder = folders.next();
var ssNew = SpreadsheetApp.create(targetFilename);
var copyFile = DriveApp.getFileById(ssNew.getId());
folder.addFile(copyFile);
DriveApp.getRootFolder().removeFile(copyFile);
}
Some other information about the Group Drive:
I did not create the Group Drive. It is shared with me
I am the owner of the folders in which the files and scripts reside.
I am the owner of all the files and scripts in these folders that I own too.
I have edit permissions at every level of this group drive.
there is nothing in your script above that actually does the "file copy". It just creating new empty file with SpreadsheetApp.create(targetFilename) and adding that to the folder.
To make a copy of the Google Sheet, you may refer to the answer at Google App Script: How do I make copy of spreadsheet and save it to particular folder?
I ended up moving that block of code to the end of the script after the data processing occurs. For some reason, within my own drive, it didn't matter when I added the file to another folder, the script would still update all instances of that file. However, within a group drive, only the file within my own root was being updated (till I moved that block of code to the end of the script).
Any explanations on why this occurs is welcome.

Create a new Google Sheet in a specific drive folder

Using a standalone script, I want to create a new sheet in a given folder.
function criaSheet(){
var folder = DriveApp.getFolderById('ID');
folder.createFile('new Spreadsheet', '', MimeType.GOOGLE_SHEETS)
}
This code asks me to use Google Advanced Services, which one?
And this code creates the sheet in the root folder:
function criaSheet(){
SpreadsheetApp.create('mySheet')
}
You may need to create a new spreadsheet file, then move it to the folder, then delete the original:
function createNewFile(){
var newSS = SpreadsheetApp.create('AAAA11111');
var newID = newSS.getId();
var folder = DriveApp.getFolderById('your folder ID');
var newFile = DriveApp.getFileById(newID);
newFile.makeCopy(folder);
//Delete original file
DriveApp.removeFile(newFile);
};
DriveApp.removeFile() seems to be removing the file without sending it to the trash. Which is fine by me, but Google Drive seems to be doing some weird stuff lately. From the Drive "Details" section, I can open the deleted file, even though there is no trace of it anywhere in any of my folders, including the trash.
If you want to try to figure out the Advanced Drive Service:
In the script editor, choose the Resources menu and Advanced Google Services.
Then turn the Drive API on:

Script to unzip attachment

I was trying to create a Google Apps Script, that takes attachment of e-mails, unzips it a forwards it. I saw unpacking feature in Google Drive (you can upload a file there, open it and copy individual files to you drive). Is this functionality accessible from Google Apps Script somehow?
First you need to write a script for automatically makes attachments of an email as directly uploaded on user's Google Drive after this trigger run this piece of code shown below
function testzip(){
var files=DocsList.getRootFolder().find('Sans titre.txt.zip');
var zipblob=files[0].getBlob();
var unzipblob = Utilities.unzip(zipblob);
var unzipstr=unzipblob[0].getDataAsString();// it is a text file
DocsList.createFile('Sans titre.txt',unzipstr);// I kept the original name to make it simple
}
Check this code. Don't blame me if it won't work. It's just a proposal.
Comment: Files are blobs so need to call getBlob(). Anything that has a getBlob() function can be used as a blob directly. You can replace
var zipblob=files[0].getBlob();
var unzipblob = Utilities.unzip(zipblob);
with this:
var zipfile=files[0];
var unzipblob = Utilities.unzip(zipfile);
I tried to edit the other answer, but someone who apparently didn't try the code rejected the edit as incorrect.