我有此脚本可以删除Google云端硬盘中的所有._*
个文件。但是有数百万个文件,并且脚本在5分钟左右退出并且“超过最长执行时间。”
function TrashDotFiles() {
var files = DriveApp.getFiles();
while (files.hasNext()) {
var file = files.next();
var name = file.getName();
if (name.indexOf("._")==0) {
console.log(name + " • trashed");
file.setTrashed(true)
}
}
}
如何让此脚本运行足够长时间来扫描整个云端硬盘?
答案 0 :(得分:2)
可能的解决方法之一是在模态窗口中运行纯JavaScript代码,该代码没有运行时限:
function onOpen()
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('Trash dot files')
.addItem('Run', 'openWindow')
.addToUi();
}
function openWindow()
{
var ui = SpreadsheetApp.getUi();
// get template
var template = HtmlService.createTemplateFromFile('deleteDriveFiles');
// need to have next line of text somewhere (even commented out) to trigger correct scopes for script and token:
// DriveApp.getFiles()
// pass token
template.data = {
token: ScriptApp.getOAuthToken()
};
// get output html
var html = template.evaluate();
// show modal window
ui.showModalDialog(html, 'Delete files from Drive');
}
[文件 - 新建 - Html文件] deleteDriveFiles.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
// used for visual log
function addParagraph(text)
{
var node = document.createElement('p');
node.innerText = text;
document.body.appendChild(node);
}
// for stats
var totalProcessed = 0;
var totalTrashed = 0;
function reqListener(){
// get response obj
var res = JSON.parse(this.responseText);
if (res.items && res.items.length)
{
// loop files
for (var i = 0; i < res.items.length; i++)
{
var file = res.items[i];
// delete file
if (file.title.indexOf('._') == 0)
{
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', function(){
// get response obj
var res = JSON.parse(this.responseText);
// sucessfully trashed
if (this.status == 200)
{
totalTrashed++;
addParagraph('Trashed '+res.title);
}
}.bind(xhr));
xhr.open('POST', 'https://www.googleapis.com/drive/v2/files/'+file.id+'/trash');
xhr.setRequestHeader('Authorization', 'Bearer <?=data.token?>');
xhr.send();
}
}
// for stats
totalProcessed += res.items.length;
}
// get next page of results
if (res.nextPageToken)
{
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', reqListener);
xhr.open('GET', 'https://www.googleapis.com/drive/v2/files?trashed=false&pageToken='+res.nextPageToken);
xhr.setRequestHeader('Authorization', 'Bearer <?=data.token?>');
xhr.send();
}
// finished
else
{
addParagraph('Finished. Processed total: '+totalProcessed+'. Trashed total: '+totalTrashed);
}
}
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', reqListener);
xhr.open('GET', 'https://www.googleapis.com/drive/v2/files?trashed=false');
xhr.setRequestHeader('Authorization', 'Bearer <?=data.token?>');
xhr.send();
</script>
</body>
</html>
保存代码更改并刷新电子表格网页后,您将看到新的菜单项:
点击运行开始处理文件。
结果: