This code will return all the file ID's of files that are older than 30 days old. It is very different than the code referenced in the other post. The code that you are using has a deprecated class in it. DocsList is now deprecated. The code I'm giving you uses DriveApp, and makes use of the searchFiles()
method.
Google Documentation - Search Files
gs Script
function getFilesByDate() {
var arrayOfFileIDs = [];
var ThirtyDaysBeforeNow = new Date().getTime()-3600*1000*24*30;
// 30 is the number of days
//(3600 seconds = 1 hour, 1000 milliseconds = 1 second, 24 hours = 1 day and 30 days is the duration you wanted
//needed in yr-month-day format
var cutOffDate = new Date(ThirtyDaysBeforeNow);
var cutOffDateAsString = Utilities.formatDate(cutOffDate, "GMT", "yyyy-MM-dd");
//Logger.log(cutOffDateAsString);
var theFileID = "";
//Create an array of file ID's by date criteria
var files = DriveApp.searchFiles(
'modifiedDate < "' + cutOffDateAsString + '"');
while (files.hasNext()) {
var file = files.next();
theFileID = file.getId();
arrayOfFileIDs.push(theFileID);
//Logger.log('theFileID: ' + theFileID);
//Logger.log('date last updated: ' + file.getLastUpdated());
}
return arrayOfFileIDs;
//Logger.log('arrayOfFileIDs: ' + arrayOfFileIDs);
};
You can un-comment the Logger.log()
statements, run the code, and review what the code returns if you want. The following Logger.log()
statement:
//Logger.log('date last updated: ' + file.getLastUpdated());
will print the dates of the files that were retrieved.
The above code doesn't delete any files, or set anything to trashed. It just searches files by date, and creates an array of all the file IDs.
So the function to delete or trash the files could first call that function and get a list of all the file ID's to work on.
It's a good idea to test the code without deleting any files first to make sure that the code is getting the correct files before running a version that deletes anything.
If you want to delete your files without first setting them to trashed, that can be done.
The example below uses the Advanced Google Drive Service. Refer to the documentation for the current way to enable the Advanced Drive Service.
//To delete a file without first sending it to the trash requires the Advanced Drive API to be enabled
function deleteFile(idToDLET) {
idToDLET = 'the File ID';
//This deletes a file without needing to move it to the trash
var rtrnFromDLET = Drive.Files.remove(idToDLET);
}
To call the function that gets the file ID's to delete, it would look like this:
WARNING! THIS DELETES FILES WITHOUT SENDING THEM TO THE TRASH! **** MAKE SURE YOU KNOW WHAT IS BEING DELETED!
function deleteFiles() {
var arrayIDs = getFilesByDate();
for (var i=0; i < arrayIDs.length; i++) {
Logger.log('arrayIDs[i]: ' + arrayIDs[i]);
//This deletes a file without needing to move it to the trash
var rtrnFromDLET = Drive.Files.remove(arrayIDs[i]);
}
};