How to delete a File in Google Drive?
Asked Answered
R

7

25

How do I write a Google Apps Script that deletes files?

This finds files:

var ExistingFiles = DocsList.find(fileName);

But DocsList.deleteFile does not exist to delete a file.

Is there a way to move those files to another Folder or to Trash?

The other workaround I would consider is to be able to override an existing file with the same name.

Currently when I want to create a file with a name already used in MyDrive then it creates a second file with the same name. I would like to keep 1 file (the new one is kept and the old one is lost).

Rattle answered 9/1, 2013 at 16:1 Comment(0)
C
27

There are 3 services available to delete a file.

  • DriveApp - Built-in to Apps Script
  • Advanced Drive Service - Built-in to Apps Script but must be enabled. Has more capability than DriveApp
  • Google Drive API - Not built-in to Apps Script, but can be used from Apps Script using the Drive REST API together with UrlFetchApp.fetch(url,options)

The DocsList service is now deprecated.

The Advanced Drive Service can be used to delete a file without sending it to the trash. Seriously consider the risk of not being able to retrieve the deleted file. The Advanced Drive Service has a remove method which removes a file without sending it to the trash folder. Advanced services have many of the same capabilities as the API's, without needing to make an HTTPS GET or POST request, and not needing an OAuth library.

function delteFile(myFileName) {
  var allFiles, idToDLET, myFolder, rtrnFromDLET, thisFile;

  myFolder = DriveApp.getFolderById('Put_The_Folder_ID_Here');

  allFiles = myFolder.getFilesByName(myFileName);

  while (allFiles.hasNext()) {//If there is another element in the iterator
    thisFile = allFiles.next();
    idToDLET = thisFile.getId();
    //Logger.log('idToDLET: ' + idToDLET);

    rtrnFromDLET = Drive.Files.remove(idToDLET);
  };
};

This combines the DriveApp service and the Drive API to delete the file without sending it to the trash. The Drive API method .remove(id) needs the file ID. If the file ID is not available, but the file name is, then the file can first be looked up by name, and then get the file ID.

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 Cloud Platform. If it's not turned on in BOTH places, it won't be available.

Corking answered 15/6, 2014 at 5:52 Comment(3)
How do you get the Folder ID? Is it possible to get it in the graphical UI?Imray
You can get the Folder ID from the browser's address bar. In Google Drive, double click on the folder, and then look in the address bar of the browser. The folder ID is in the URL. Is that what you want?Corking
You can move a file to the trash using DriveApp service through the file's .setTrashed() method. thisFile.setTrashed(true);Asterism
S
20

Now you may use the following if the file is as a spreadsheet, doc etc.:

 DriveApp.getFileById(spreadsheet.getId()).setTrashed(true);

or if you already have the file instead of a spreadsheet, doc etc. you may use:

file.setTrashed(true);
Schurman answered 25/12, 2016 at 5:54 Comment(0)
D
9

This code uses the DocsList Class which is now deprecated.

try this :

function test(){
deleteDocByName('Name-of-the-file-to-delete')
}

function deleteDocByName(fileName){
  var docs=DocsList.find(fileName)
    for(n=0;n<docs.length;++n){
     if(docs[n].getName() == fileName){
      var ID = docs[n].getId()
      DocsList.getFileById(ID).setTrashed(true)
      }
     }
    }

since you can have many docs with the same name I used a for loop to get all the docs in the array of documents and delete them one by one if necessary.

I used a function with the filename as parameter to simplify its use in a script, use test function to try it.

Note : be aware that all files with this name will be trashed (and recoverable ;-)

About the last part of your question about keeping the most recent and deleting the old one, it would be doable (by reading the last accessed date & time) but I think it is a better idea to delete the old file before creating a new one with the same name... far more logical and safe !

Doublehung answered 9/1, 2013 at 16:13 Comment(2)
@Sergeinsas I know this is a dated question, but I'm hoping you can still help in respect to creating a loop that would delete older files vs newer ones. I'm trying to figure out how to look at all the files in a folder that will always have 6 files whose names will stay consistent, so I just need a routine script that will delete the older versions of each files every 24 hours. I know it's not the safest option, but it's one of the best options given my situation. Especially since it's only myself managing these files, no Drive-sharing.Swainson
please post a new question, your request is too different and this post is outdated... thxDoublehung
S
3

Though the The service DocsList is now deprecated, as from the Class Folder references, the settrashed method is still valid:

https://developers.google.com/apps-script/reference/drive/folder#settrashedtrashed

So should work simply this:

ExistingFiles.settrashed(true);
Septicidal answered 6/5, 2016 at 18:22 Comment(1)
is there a way to add in if file exists in then skip or loop?Slipknot
W
2

Here is another way to do it without the need of Drive API. (based on Allan response).

function deleteFile(fileName, folderName) {
  var  myFolder, allFiles, file;
  myFolder = DriveApp.getFoldersByName(folderName).next();

  allFiles = myFolder.getFilesByName(fileName);

  while (allFiles.hasNext()) {
    file = allFiles.next();
    file.getParents().next().removeFile(file);
  }
}
Wallenstein answered 8/5, 2019 at 17:46 Comment(1)
You can just use file.setTrashed(true); instead of file.getParents().next().removeFile(file);.Asterism
C
0

Here is a slightly modified version using the above. This will backup said file to specified folder, also remove any old previous backups with the same name so there are no duplicates.

The idea is here to backup once per day, and will retain 1 month of backups in your backup folder of choice. Remember to set your trigger to daily in your Apps Script.

https://gist.github.com/fmarais/a962a8b54ce3f53f0ed57100112b453c

function archiveCopy() {
  var file = DriveApp.getFileById("original_file_id_to_backup");
  var destination = DriveApp.getFolderById("backup_folder_name");

  var timeZone = Session.getScriptTimeZone();
  var formattedDate = Utilities.formatDate(new Date(),timeZone,"dd"); // 1 month backup, one per day
  var name = SpreadsheetApp.getActiveSpreadsheet().getName()+"_"+formattedDate;

  // remove old backup
  var allFiles = destination.getFilesByName(name);
  while (allFiles.hasNext()) {
    var thisFile = allFiles.next();
    thisFile.setTrashed(true);
  };

  // make new backup
  file.makeCopy(name,destination); 
}
Colous answered 12/5, 2022 at 13:51 Comment(0)
J
0

I took hint from Riyafa and modified my script with below:

  while (files.hasNext()){
     var file = files.next();
     if(file==pdfName+".pdf"){
         DriveApp.getFileById(file.getId()).setTrashed(true);
     }
  }

No more accumulation of duplicate files.

Jenness answered 27/3, 2023 at 3:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.