Reputation: 21
I am trying to automate acceptance of pending ownership requests for thousands of files on a Google Drive using Google Apps Script.
Here is my script.
function ownPendingFiles() {
const OLD_OWNER1 = '[accountA]@gmail.com';
const NEW_OWNER = '[accountB]@gmail.com';
const QUERY = `"${OLD_OWNER1}" in owners and "${NEW_OWNER}" in writers` // query files owned by the sender and writable by the receiver
var fileIter = DriveApp.searchFiles(QUERY); // return files matching the query
const emailPermId = Drive.Permissions.getIdForEmail(NEW_OWNER).id; // get receiver's permission ID
var fileList = []; // create an empty array for file IDs and information on pending ownership
while (fileIter.hasNext()) { // for each file found, return its permissions
var file = fileIter.next();
var fileId = file.getId();
var filePermForEmail = Drive.Permissions.get(fileId, emailPermId); // get file permissions for receiver
fileList.push([fileId,filePermForEmail.pendingOwner]); // write pending ownership information for files
}
var fileListToOwn = fileList.filter(file => file[1]===true); // select files with pending ownership requests
var fileListToOwnIds = [];
for(let i = 0, l = folderListToOwn.length; i < l; i++) { // create a list of file ids to own
fileListToOwnIds.push(fileListToOwn[i][0]);
var filesToOwn = DriveApp.getFileById(fileListToOwnIds[i]);
Logger.log(filesToOwn.setOwner(NEW_OWNER))
}
}
The script works well for a small number of requests, but fails for thousands, returning the 'Exceeded maximum execution time' error.
I am new to GAS and I could not implement workarounds for this problem reported elsewhere.
What would be a way to make the script work?
Upvotes: 1
Views: 567
Reputation: 1343
In your case you are reaching the total execution time as your code is currently looping over a thousand times, I would suggest checking how to perform batch operations in Apps script.
The specific part you can improve is this snippet of your code:
for(let i = 0, l = folderListToOwn.length; i < l; i++) { // create a list of file ids to own
fileListToOwnIds.push(fileListToOwn[i][0]);
var filesToOwn = DriveApp.getFileById(fileListToOwnIds[i]);
Logger.log(filesToOwn.setOwner(NEW_OWNER))
}
In this portion of your code you are looping too many times over the DriveApp.getFileById()
method thus you receive the maximum execution time.
Upvotes: 1