Einarr
Einarr

Reputation: 332

Delete all but x most resent files in a folder Google script

I have a folder where I store backup files and I want to keep only the 5 most recent files

All files are in a folder called New Project Backups

All files have New Project as part of their name

I found this here Delete old files

How do I focus the Function to look in only the folder New Project Backups

Thanks

function myFunction() {
  var file_iterator = DriveApp.getFiles();

  var file_list = [];
  while (file_iterator.hasNext()) {
    var fl = file_iterator.next();
    if (fl.getName().match("New Project"))
      file_list.push(fl); 
  }

  // Sort the files on date created
  file_list = file_list.sort(function(fl1, fl2) {
    return fl1.getDateCreated() < fl2.getDateCreated();
  });

  // Removing uneeded file
  while (file_list.length > 5) {
    var fl = file_list.pop();
    // fl.setTrashed(true); // if you want it in the trash
                        // instead of fully removed.
    DriveApp.removeFile(fl);
 }
 } 

Upvotes: 2

Views: 1072

Answers (1)

helcode
helcode

Reputation: 2048

Using DriveApp.getFiles() will get you all files in the drive. you can fix that by replacing

  var file_iterator = DriveApp.getFiles();

with

  id = "0XrUxpDX-E8dpeE9EQmpYLeplOLB";
  var folders = DriveApp.getFolderById(id);
  var file_iterator = folders.getFiles();

the id is the folder id you want to work with, you can find it from the folder URL

Example, Folder URL: https://drive.google.com/drive/u/1/folders/0XrUxpDX-E8dpeE9EQmpYLeplOLB Folder ID: 0XrUxpDX-E8dpeE9EQmpYLeplOLB

enjoy ;)

Upvotes: 2

Related Questions