Advertisement
ghiwar

Auto Delete Gdrive Files After x Day/Hour and Auto empty Trash

Jan 22nd, 2025
49
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. function deleteFilesOlderThan26Hours() {
  2.   var folder = DriveApp.getFolderById("FOLDER-ID");
  3.   var files = folder.getFiles(); // Get all files in the folder
  4.   var now = new Date(); // Current time
  5.   var hoursLimit = 26; // Time limit in hours (26 hours)
  6.  
  7.   while (files.hasNext()) {
  8.     var file = files.next();
  9.     var lastUpdated = file.getLastUpdated(); // Get the last updated date of the file
  10.     var diffHours = (now - lastUpdated) / (1000 * 60 * 60); // Calculate the difference in hours
  11.  
  12.     // Log file details for debugging
  13.     Logger.log("File: " + file.getName());
  14.     Logger.log("Last Updated: " + lastUpdated);
  15.     Logger.log("Age (hours): " + diffHours);
  16.  
  17.     if (diffHours > hoursLimit) {
  18.       Logger.log("Moving file to Trash: " + file.getName());
  19.       file.setTrashed(true); // Move the file to Trash
  20.     } else {
  21.       Logger.log("File not old enough for deletion: " + file.getName());
  22.     }
  23.   }
  24.   // Permanently empty Trash
  25.   try {
  26.     Drive.Files.emptyTrash(); // Requires Drive API
  27.     Logger.log("Trash has been emptied!");
  28.   } catch (error) {
  29.     Logger.log("Failed to empty Trash: " + error.message);
  30.   }
  31.  
  32.   Logger.log("File processing complete.");
  33. }
  34.  
Advertisement
Comments
  • ghiwar
    6 hours
    # text 0.09 KB | 0 0
    1. This script running on Google apps Script https://script.google.com/
    2.  
    3. Created by t.me/mase89
Add Comment
Please, Sign In to add comment
Advertisement