3

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.

tehhowch
  • 9,645
  • 4
  • 24
  • 42
il_Cozzimo
  • 112
  • 3
  • 11

1 Answers1

2

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?

tehhowch
  • 9,645
  • 4
  • 24
  • 42
  • Hi tehhowch, thank you very much for your answer! your first proposition worked perfectly. I marked this topic as a duplicate as the other question was speaking about Drive.Files.remove(file.id) too. – il_Cozzimo Apr 13 '18 at 10:00