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");
// 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.