问题
I created this script to delete files published more than 3 hours ago. And even if the latest file is older than 3 hours, it will not be deleted, so the folder will never be empty.
I enabled google's advanced service called DRIVE API V2.
I activated a trigger to analyze the folder every 5 minutes, but often the files are not deleted, they remain in the folder. The script works sometimes yes and sometimes no.
I would like to know what is wrong or what I need to edit to make it work perfectly.
function getOldFileIDs() {
// Old date is 3 Hours
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('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
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;
};
function deleteFiles() {
var fileIDs = getOldFileIDs();
fileIDs.forEach(function(fileID) {
Drive.Files.remove(fileID);
});
};
I also want some help so that this script can analyze if there are files with the same name inside the folder, if it exists, it delete surplus ones so that there is always only one file with each name.
And new detail, a new error appeared that until earlier did not happen ... Saying that:
API call failed for drive.files.delete with error Insufficient permissions for this file (line 24)
Line 24:
Drive.Files.remove(fileID);
回答1:
By using consumer (free) accounts, only the file owner is able to delete them. To prevent the error, before calling Drive.Files.remove(fileID)
your code should check if you are the file owner.
Related
- Is it possible to get the owner for a Google Drive file?
- How to get the owner of file using Google Drive API
- How to programmticly remove a file from "share wtih me" in Google drive
- How to retrieve the owner or Drive ID of a document with Google APIs?
回答2:
Try this:
obj.sort(function(a, b) {
var a=new Date(a.date).valueOf();
var b=new Date(b.date).valueOf();
return b-a;
});
来源:https://stackoverflow.com/questions/58228969/delete-old-files-from-a-google-drive-folder