I have this script that deletes old files from Google Drive ... I would like to adjust it so that it deletes files from a specific folder, specifically files that were created over 3 hours ago. And one more detail, the folder cannot be empty, so the latest file even if it has been published for more than 3 hours cannot be deleted. It can only be deleted when another file is added in the folder. I need help getting this done, I can't edit the script for these details.
function getOldFileIDs() {
var fileIDs = [];
// Old date is 30 days
var oldDate = new Date().getTime() - 3600*1000*24*30;
var cutOffDate = Utilities.formatDate(new Date(oldDate), "GMT", "yyyy-MM-dd");
// Get folderID using the URL on google drive
var folder = DriveApp.getFolderById('XXXXXXX');
var files = folder.searchFiles('modifiedDate < "' + cutOffDate + '"');
while (files.hasNext()) {
var file = files.next();
fileIDs.push(file.getId());
Logger.log('ID: ' + file.getId() + ', Name: ' + file.getName());
}
return fileIDs;
};
function deleteFiles() {
var fileIDs = getOldFileIDs();
fileIDs.forEach(function(fileID) {
DriveApp.getFileById(fileID).setTrashed(true);
});
};
modifiedDate < 3 hours
.If my understanding is correct, how about this modification?
modifiedDate
, it seems that the ISO format is required to be used.When above point and modifiedDate < 3 hours
are reflected to your script, it becomes as follows.
When your script is modified, please modify as follows.
From:var oldDate = new Date().getTime() - 3600*1000*24*30;
var cutOffDate = Utilities.formatDate(new Date(oldDate), "GMT", "yyyy-MM-dd");
var oldDate = new Date().getTime() - 3600*1000*3;
var cutOffDate = new Date(oldDate).toISOString();
If I misunderstood your question and this was not the result you want, I apologize.
modifiedDate < 3 hours
.If my understanding is correct, how about this modification?
Please modify the function of getOldFileIDs()
as follows.
function getOldFileIDs() {
// Old date is 30 days
var oldDate = new Date().getTime() - 3600*1000*3;
var cutOffDate = new Date(oldDate).toISOString();
// Get folderID using the URL on google drive
var folder = DriveApp.getFolderById('XXXXXXX');
var files = folder.searchFiles('modifiedDate < "' + cutOffDate + '"');
var obj = [];
while (files.hasNext()) {
var file = files.next();
obj.push({id: file.getId(), date: file.getDateCreated()});
}
obj.sort(function(x, y) {return x.date < y.date ? 1 : -1});
obj.shift();
var fileIDs = obj.map(function(e) {return e.id});
return fileIDs;
};
If my understanding is correct, how about this modification?
Please modify the function of deleteFiles()
as follows. Before you run the script, please enable Drive API at Advanced Google services.
DriveApp.getFileById(fileID).setTrashed(true);
To:
Drive.Files.remove(fileId);