Skip to content

Instantly share code, notes, and snippets.

@leoherzog
Created February 27, 2018 14:50
Show Gist options
  • Select an option

  • Save leoherzog/05b57f096b40c5bc821b09dcf1df5a3b to your computer and use it in GitHub Desktop.

Select an option

Save leoherzog/05b57f096b40c5bc821b09dcf1df5a3b to your computer and use it in GitHub Desktop.
[Google Apps Script] Change Owner of Google Drive Folder and All It's Contents
var allFolders = [];
var allFiles = [];
function changeOwnership() {
var newOwner = "new.owner@gmail.com";
var folderIdToChange = "0B7uECGWKsTGu712INmZSYzReSBE";
// update the global allFiles and allFolders arrays
allFolders.push(DriveApp.getFolderById(folderIdToChange));
recursivelyGetAllFilesAndFolders(folderIdToChange);
Logger.log("Got all of the folders and files. Updating ownership...");
for (var i in allFolders) {
try {
allFolders[i].setOwner(newOwner);
}
catch(e) {
Logger.log("Problem updating ownership for the file " + allFolders[i].getName() + ". Continuing...");
}
}
for (var i in allFiles) {
try {
allFiles[i].setOwner(newOwner);
}
catch(e) {
Logger.log("Problem updating ownership for the file " + allFiles[i].getName() + ". Continuing...");
}
}
Logger.log("Updating complete! Pew pew.");
return;
}
function recursivelyGetAllFilesAndFolders(parent) {
parent = DriveApp.getFolderById(parent);
var childFolders = parent.getFolders();
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
allFolders.push(childFolder);
var files = childFolder.getFiles();
while (files.hasNext()) {
allFiles.push(files.next());
}
// Recursive call for any sub-folders
recursivelyGetAllFilesAndFolders(childFolder.getId());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment