Apps Script Function to set a file backup limit

23 views
Skip to first unread message

C Lee

unread,
Sep 16, 2025, 1:27:10 PM (7 days ago) Sep 16
to Google Apps Script Community
Hello,

I have a function I am running currently to backup one of my spreadsheets to a folder on Google Drive daily.  The function seems to have everything I want except for a limit on how many files i store:

function myFunctionArchiveCopy() {
var file=DriveApp.getFileById("1M1qJXNn-Q8bs-p14UP57NCrAIakRlw4UXmytsWCbpSI");
var destination= DriveApp.getFolderById("1yjB9Ha82WUs9I80WRoPhmZag2SdPBvAZ");
var timeZone=Session.getScriptTimeZone();
var formattedDate= Utilities.formatDate(new Date(),timeZone,"yyy-MM-dd' 'HH:mm:ss");
var name= SpreadsheetApp.getActiveSpreadsheet().getName()+"Copy"+formattedDate;
  file.makeCopy(name,destination);
 
}

I would like to add a line in here that will remove the oldest file and stores a new file, keeping 30 files in the directory, like "var backups=30" but even when I put that value in there and the function runs properly, it just makes a new backup and doesn't remove file 31, 32, 33, etc.  If there a variable I am missing in order for it to purge older files and only store 30?

Keith Andersen

unread,
Sep 16, 2025, 3:41:02 PM (7 days ago) Sep 16
to google-apps-sc...@googlegroups.com
Lee, I'm away from my computer right now but I ran it through Gemini and this should get you started. I will be on my computer later and test it also and help if there's any bugs. 

The script you have now makes a copy of the file and stores it in the designated folder. It doesn't have any built-in logic to manage the number of files. You'll need to add that logic yourself.
How to manage the number of files
You need to do the following:
 * List existing backups: Get a list of all files in the destination folder.
 * Check the count: See if the number of files exceeds your limit (30).
 * Sort the files: Order the files by their creation date to find the oldest one.
 * Remove the oldest file: If the number of files is over the limit, delete the oldest file.
Example code to add to your function
Here's an updated version of your script that incorporates the file management logic:
function myFunctionArchiveCopy() {
  
  // Set your limit
  var backupsLimit = 30;

  var file = DriveApp.getFileById("1M1qJXNn-Q8bs-p14UP57NCrAIakRlw4UXmytsWCbpSI");
  var destination = DriveApp.getFolderById("1yjB9Ha82WUs9I80WRoPhmZag2SdPBvAZ");
  var timeZone = Session.getScriptTimeZone();
  var formattedDate = Utilities.formatDate(new Date(), timeZone, "yyyy-MM-dd' 'HH:mm:ss");
  var name = SpreadsheetApp.getActiveSpreadsheet().getName() + "Copy" + formattedDate;

  // Make the new copy
  file.makeCopy(name, destination);

  // Get all files in the destination folder and sort them by creation date
  var files = destination.getFiles();
  var filesList = [];
  while (files.hasNext()) {
    filesList.push(files.next());
  }

  // Sort files from oldest to newest
  filesList.sort(function(a, b) {
    return a.getDateCreated().getTime() - b.getDateCreated().getTime();
  });

  // Check if we need to delete older files
  if (filesList.length > backupsLimit) {
    var filesToDelete = filesList.length - backupsLimit;
    for (var i = 0; i < filesToDelete; i++) {
      filesList[i].setTrashed(true); // Move oldest file to trash
    }
  }
}

Explanation of the new lines
 * var backupsLimit = 30;: This variable sets the maximum number of files you want to keep. You can easily change this number.
 * var files = destination.getFiles();: This gets a FileIterator object, which is used to loop through the files.
 * var filesList = []; and while (files.hasNext()) { ... }: This loop converts the iterator into an array (filesList) so you can sort the files.
 * filesList.sort(...): This sorts the filesList array based on the creation date of each file, from oldest to newest.
 * if (filesList.length > backupsLimit): This checks if the total number of files in the folder has exceeded your set limit.
 * filesList[i].setTrashed(true);: This line is inside a for loop that runs for each file that needs to be deleted. It moves the oldest file (the first element in the sorted array) to the trash.




My website: https://sites.google.com/view/klaweb/
Passions: God, Family, Scriptures, Learning, Data Management, Google Sheets + App Script and much more!

--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/google-apps-script-community/64167f24-350a-4812-96c9-15cfc6fedbebn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages