André Páscoa
André Páscoa

Reputation: 111

Google Apps Script to delete all files from google drive?

I need to delete all files from my drive, more than 16 GB and I'm getting hours manually deleting.

Sought help in support of google and had no help.

Can I move a Google Apps Script that I execute?

Upvotes: 10

Views: 12760

Answers (3)

Lockszmith
Lockszmith

Reputation: 2551

Combining the excellent work of both patt0 and Serge insas along with Sandy Good's answer about permanent removal, I am sharing my own final version of this script.

First, make sure to following the instructions in Sandy Good's answer, without it, the script will not be able to permanently remove files (you can still Trash the files though).

Features of script:

  • Stackdriver Logging - every 50 files processed, a log message issues with status.
    I recommend adding severity!=ERROR to the filter, while tracking progress.
  • Skip on error - There are files that will fail to remove (most commonly files shared with you, which you don't own, and thus don't have permissions to delete), these files are logged.
  • Continuation
    Scripts on script.google.com are limited to run for a duration not longer than 30 minutes.
    When this script fails/times-out, you will be able to run it again, and it will continue where it stopped.

What this script DOES NOT do:

  • 3rd Party Application data is not touched, and will still require manual removal. (A good example of a space-hogging app: WhatsApp backup)

Danger Zone

This scripts will delete everything it can in the allotted time it has to run, because of that I've commented out the actual removal/trashing of the file (same as in the other answers).
To actually perform the removal/trashing, uncomment the relevant lines.

Good Luck.
- Famous last words

The code

Also available via this direct link: (https://lksz.me/GoogleDriveCleaner)

    // dont-delete-me-secret-code-1Nq0feuBuyGy5KWGqzEnvXODWx519Ka1aNSlXF_Bg6q1yP
    // Link to this script: https://lksz.me/GoogleDriveCleaner
    // Script based on the StackOverflow answers at:
    //      https://stackoverflow.com/a/25750738
    // and  https://stackoverflow.com/a/19616656 and https://stackoverflow.com/a/19615407
    //
    // You might need to run processAllFiles() multiple times.
    // To start from scratch, first run clearContinuationToken()
    //
    // Last modified Nov 22, 2018
    //
    function processAllFiles() {
      var usrP = PropertiesService.getUserProperties();

      var continuationToken = usrP.getProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN');
      var numberOfFiles = Number(usrP.getProperty('Number_of_files_processed'));
      var numberOfErrors = Number(usrP.getProperty('Number_of_files_failed'));

      var thisScriptFileId = DriveApp
            .searchFiles('fullText contains "// dont-delete-me-secret-code-1Nq0feuBuyGy5KWGqzEnvXODWx519Ka1aNSlXF_Bg6q1yP"')
            .next()
            .getId();

      Logger.log("thisScriptFileId = " + thisScriptFileId);
      if (continuationToken == null) {
        var files = DriveApp.getFiles();
        var continuationToken = files.getContinuationToken();
        usrP.setProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN', continuationToken);
        usrP.setProperty('Number_of_files_processed', '0');
        usrP.setProperty('Number_of_files_failed', '0');
      } else {
        var files = DriveApp.continueFileIterator(continuationToken);
      }

      while (files.hasNext()) {
        var file = files.next();
        var fileID = file.getId();
        if(fileID!=thisScriptFileId){
          try {
            // Log advancement
            if( 1 == (numberOfErrors + numberOfFiles) % 50 ) {
              var msg = Utilities.formatString("%05d", numberOfFiles + numberOfErrors) + ', next file is: ' + file.getName();

              console.log({message: msg, numberOfFiles: numberOfFiles, numberOfErrors: numberOfErrors, total: numberOfFiles + numberOfErrors });
              Logger.log(msg);

              usrP.setProperty('Number_of_files_processed', numberOfFiles);
              usrP.setProperty('Number_of_files_failed', numberOfErrors);
            }

            // Un-comment one of the options below.
            // Option 1: Permanent removal
            // Follow instructions in https://stackoverflow.com/a/25750738 to enable Drive API
            // Drive.Files.remove(fileID);

            // Option 2: Trash file, will need to empty trash after script runs.
            // file.setTrashed(true);

            numberOfFiles++;
          } catch (e) {
            numberOfErrors++;
            var msg = Utilities.formatString("%05d", numberOfFiles + numberOfErrors) + ', failed to remove file: ' + file.getName();

            console.error({message: msg, numberOfFiles: numberOfFiles, numberOfErrors: numberOfErrors, total: numberOfFiles + numberOfErrors });
            Logger.log(msg);
          }
        }
      }

      // finish processing delete the token
      clearContinuationToken();
    }

    function clearContinuationToken() {
      var usrP = PropertiesService.getUserProperties();
      usrP.deleteProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN');
      usrP.deleteProperty('Number_of_files_processed');
      usrP.deleteProperty('Number_of_files_failed');
      console.log({message: 'clearContinuationToken - Logging test', values: 1, testing: "bubu"});
    }

    function processAllFolder() {
      // Log the name of every folder in the user's Drive.
      var folders = DriveApp.getFolders();
      while (folders.hasNext()) {
        var folder = folders.next();
        console.log(folder.getName());
        // folder.setTrashed(true);
      }
    }

Upvotes: 0

patt0
patt0

Reputation: 800

I am going to assume you are familiar with Google Apps Script to the point where you know how to create a script in your drive, manage the editor etc ... if you are not please start here https://developers.google.com/apps-script/overview.

Here a little script that will list all your files and set them to the trash, you will still need to go to trash and delete forever.

BE CAREFUL WHEN USING THIS SCRIPT : MOVES ALL FILES TO TRASH

You will need to uncomment the file.setTrashed(true) when you run this

function processAllFiles() {
  // we look for the continuation token from the UserProperties
  // this is useful as the script may take more that 5 minutes 
  // (exceed execution time)
  var continuationToken = UserProperties.getProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN');

  if (continuationToken == null) {
    // firt time execution, get all files from drive
    var files = DriveApp.getFiles();
    // get the token and store it in a user property
    var continuationToken = files.getContinuationToken();
    UserProperties.setProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN', continuationToken);
  } else {
    // we continue to execute (and move everything to trash)
    var files = DriveApp.continueFileIterator(continuationToken);
  }

   while (files.hasNext()) {
     var file = files.next();
//     file.setTrashed(true);
     Logger.log(file.getName());
  }

  // finish processing delete the token
  UserProperties.deleteProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN');
}

You might potentially be left with very many folders (if they were created programatically for some reason ;) ) so you could run this little script to move them to the trash aw well. Don't forget to uncomment the line that counts below.

function processAllFolder() {
// Log the name of every folder in the user's Drive.
  var folders = DriveApp.getFolders();
  while (folders.hasNext()) {
    var folder = folders.next();
     Logger.log(folder.getName());
     // folder.setTrashed(true);
  }
};

Let me know how that works out for you.

Upvotes: 8

Serge insas
Serge insas

Reputation: 46794

I was very interrested by patt0's (best) answer and tried to improve it (just a little :-) by adding a few features for my personal comfort...

Here is what I came to, just for information (added data logging saved in a single document that won't be deleted so you can keep a trace of what happened - or what will happen if you run it with the commented setTrashed()- and sending a mail to you with the log data doc url for easy access)

function processAllFiles() {
  var continuationToken = UserProperties.getProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN');
  var numberOfFiles = Number(UserProperties.getProperty('Number_of_files_processed'));
  var thisScriptFileId = DocsList.find("continuationToken = UserProperties.getProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN')")[0].getId();
  Logger.log(thisScriptFileId);
  if(UserProperties.getProperty('logFileId') == null ){
    var logFileId = DocumentApp.create('Delete All Files Log data').getId();
    var doc = DocumentApp.openById(logFileId);
    doc.getBody().appendParagraph('List of all the files you deleted\n\n');
    UserProperties.setProperty('logFileId', logFileId);
  }
  if (continuationToken == null) {
    var files = DriveApp.getFiles();
    var continuationToken = files.getContinuationToken();
    UserProperties.setProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN', continuationToken);
    UserProperties.setProperty('Number_of_files_processed', '0');
  } else {
    var files = DriveApp.continueFileIterator(continuationToken);
  }

   while (files.hasNext()) {
     var file = files.next();
     if(file.getId()!=logFileId&&file.getId()!=thisScriptFileId){
//     file.setTrashed(true);
       numberOfFiles++
         Logger.log('File '+Utilities.formatString("%05d", numberOfFiles)+' : '+file.getName());
     }
   }
  var paragraphStyle = {};
  paragraphStyle[DocumentApp.Attribute.FONT_SIZE] = 8 ;

  var doc = DocumentApp.openById(UserProperties.getProperty('logFileId'));
  doc.getBody().appendParagraph(Logger.getLog()).setAttributes(paragraphStyle);
  MailApp.sendEmail(Session.getEffectiveUser().getEmail(),'DeleteFiles result Log','Here is the log data to your script :\n\n'
                    +doc.getUrl()+'\n\nExecuted by this script : '+DocsList.getFileById(thisScriptFileId).getUrl());
  // finish processing delete the token
  UserProperties.deleteProperty('DELETE_ALL_FILES_CONTINUATION_TOKEN');
  UserProperties.deleteProperty('Number_of_files_processed');
}

Upvotes: 4

Related Questions