我认为最好的方法是使用DriveApp api。
您应该使用一些功能:
-
getFiles 允许您选择所有驱动器文件
- 您收到的
FileIterator必须按照getDateCreated()排序
- 使用
removeFile api 删除最旧的文件或使用setTrashed api 将最旧的文件设置为已删除。您可以使用 Drive.Files.emptyTrash() 清空垃圾箱(这是在 Advanced Api 中)。 A 我们会看到这种方法实际上并没有完全删除文件,并且会导致意想不到的结果。
-
工作方法:必须通过advanced API
Drive.Files(请仔细阅读如何在您的脚本中启用高级API)。这还允许为您要删除的文件创建更快的查询(已经为我们组织它们的查询)
这或多或少是我为解决您的问题所做的:
// Get all the files
files_iterator = DriveApp.getFilesByType("application/7z-compressed");
var file_list = [];
while (files_iterator.hasNext()) {
var fl = files_iterator.next();
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 > 24) {
var fl = file_list.pop();
DriveApp.removeFile(fl);
}
此代码未经测试,可能包含错误。使用它需要您自担风险。
如果 Mime Type 不起作用,另一种解决方案是列出驱动器中的所有文件,并仅保留文件名以 DATABASENAME 开头的文件:
var files_iterator = DriveApp.getFiles();
var file_list = [];
while (files_iterator.hasNext()) {
var fl = files_iterator.next();
if (fl.getName().match("DATABASENAME"))
file_list.push(fl);
}
更稳定的版本
我编写了一个似乎可以正常工作的新版本:
function myFunction() {
// Query drive for the files that has name containing "DATABASENAME" as prefix
// the result (items) is ordered by creating date
var files = Drive.Files.list({
q: 'title contains "DATABASENAME"',
orderBy: 'createdDate'
}).items;
// While keeping the last 24 elements, runs a function
// for each element of the Array
files.slice(0, -25).forEach(function(file) {
// Deletes the file (recognized with its ID)
Drive.Files.remove(file.id)
});
}
如果您不启用高级 API,此功能将不起作用。我已经测试了多次,只剩下最后 24 个元素。您必须等待函数在再次运行之前结束其执行,否则数组可能会变得不一致,并且第二次执行可能会删除不需要的文件。根据您驱动器帐户中的文件数量,list 函数(作为getFiles 函数)执行counted 和limited 的查询。此操作非常昂贵,并且每小时运行一次可能会使您超出配额。我建议您每天运行一次。
list 的一个好处是它实际上允许您通过7z mimeType ("application/x-7z-compressed") 的字符串进行搜索:
Drive.Files.list({
q: 'mimeType = "application/x-7z-compressed"'
});
不推荐使用 DriveApp 的第一个版本
这是我在 AppScript 和 Drive 中实际测试过的版本:
function myFunction() {
var file_iterator = DriveApp.getFiles();
var file_list = [];
while (file_iterator.hasNext()) {
var fl = file_iterator.next();
if (fl.getName().match("DATABASENAMES"))
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 > 24) {
var fl = file_list.pop();
// fl.setTrashed(true); // if you want it in the trash
// instead of fully removed.
DriveApp.removeFile(fl);
}
}
但这个版本的问题是实际上并没有从驱动器中删除文件。我不明白为什么这个函数实际上存在,我没有看到它的用法。它只会从 view
中删除文件