Monday, February 20, 2017

Google Script to auto delete old files from a Google Drive Folder

If you are creating auto backup of any file in Google Drive using script ( either daily or on any edits ), so the number of back up file keeps on increasing. Now, if you want to delete the excessive files, for example if you want to delete all the files except the last 100 back up files, then you can achieve it by using the following script code:

//////////////////////////////////////////////////

function deleteOldSheets() {
  var df = DriveApp.getFolderById("xxx_GOOGLE_DRIVE_FOLDER_ID_xxx");
  var arr = new Array();
  var files = df.getFiles();
  while( files.hasNext() ) {
    var f = files.next();
    arr.push( [ [ f.getId() ] , [ f.getLastUpdated() ] ] );
  }
  arr.sort( sortFunction );
  
  for( var i=100 ; i<arr.length ; i++ )
    DriveApp.getFileById( arr[i][0] ).setTrashed( true );
};

function sortFunction( a , b ) {
  var aDate = new Date(a[1]);
  var bDate = new Date(b[1]);
  if ( aDate === bDate ) return 0;
  else if ( aDate < bDate ) return 1;
  else return -1;
};

//////////////////////////////////////////////////

The above script code will help you to delete the back up files ( from a Google Drive folder ) which are excessive and not required anymore, the script will move these files to "Trash".

And if you want to automatically run the above script daily, then in the script editor you can set the trigger for it.

NOTE: In the above script you'll need to replace the Google Drive folder Id.

4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. i place above script and run it but no changes?

    ReplyDelete
    Replies
    1. The Script runs just change the number of backup files you need to keep in my case i needed only one file so i changed the count and its running fine

      for( var i=1 ; i<arr.length ; i++ )- My Script
      for( var i=100 ; i<arr.length ; i++ ) - Author script

      Try now and check

      Delete