Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Updated 12 Sep 2016:</p> <p>This code uses a service account that's been granted <a href="https://developers.google.com/drive/v2/web/delegation" rel="nofollow">Google Apps Domain-Wide Delegation of Authority</a>. This lets you change the owner of any file owned by any user on the domain. This code uses the Google <a href="https://github.com/googlesamples/apps-script-oauth2" rel="nofollow">apps-script-oauth2</a> library by Eric Koleda. </p> <pre><code>var PRIVATE_KEY = PropertiesService.getScriptProperties().getProperty('PRIVATE_KEY'); var CLIENT_EMAIL = PropertiesService.getScriptProperties().getProperty('CLIENT_EMAIL'); /** * Transfers ownership of a file or folder to another account on the domain. * * @param {String} fileId The id of the file or folder * @param {String} ownerEmail The email address of the new owner. */ function transferOwnership(fileId, ownerEmail) { var file = DriveApp.getFileById(fileId); var currentOwnerEmail = file.getOwner().getEmail(); //the user that we need to impersonate var service = getService(currentOwnerEmail); if (service.hasAccess()) { var url = 'https://www.googleapis.com/drive/v2/files/' + fileId + '/permissions'; var payload = {value: ownerEmail, type: 'user', role: 'owner'}; var options = {method: "post", contentType: "application/json", headers : { Authorization: 'Bearer ' + service.getAccessToken() }, payload: JSON.stringify(payload)//, ,muteHttpExceptions: true }; //debugger; //throw 'test my errors'; var response = UrlFetchApp.fetch(url, options); if (response.getResponseCode() === 200 || (response.getResponseCode() === 400 &amp;&amp; response.getContentText().indexOf('were successfully shared')) ) { return response.getContentText(); } if (response.getResponseCode() === 401 &amp;&amp; response.getContentText().indexOf('Invalid Credentials')) { throw 'Unable to transfer ownership from owner ' + currentOwnerEmail + ' ... ' + 'Please make sure the file\'s owner has a Google Apps license (and not a Google Apps Vault - Former Employee license) and try again.'; } throw response.getContentText(); } else { throw service.getLastError(); } } /** * Reset the authorization state, so that it can be re-tested. */ function reset() { var service = getService(); service.reset(); } /** * Configures the service. */ function getService(userEmail) { return OAuth2.createService('GoogleDrive:' + userEmail) // Set the endpoint URL. .setTokenUrl('https://accounts.google.com/o/oauth2/token') // Set the private key and issuer. .setPrivateKey(PRIVATE_KEY) .setIssuer(CLIENT_EMAIL) // Set the name of the user to impersonate. This will only work for // Google Apps for Work/EDU accounts whose admin has setup domain-wide // delegation: // https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority .setSubject(userEmail) // Set the property store where authorized tokens should be persisted. .setPropertyStore(PropertiesService.getScriptProperties()) // Set the scope. This must match one of the scopes configured during the // setup of domain-wide delegation. .setScope('https://www.googleapis.com/auth/drive'); } </code></pre> <p>Old answer (obsolete now as the Document List API is deprecated):</p> <p>You can achieve this in Google Apps Script by accessing the Document List API using the raw atom xml protocol. You need to be a super admin of the domain. Here's an example that works for me:</p> <pre><code>/** * Change Owner of a file or folder * Run this as admin and authorise first in the script editor. */ function changeOwner(newOwnerEmail, fileOrFolderId){ var file = DocsList.getFileById(fileOrFolderId); var oldOwnerEmail = file.getOwner().getEmail(); if (oldOwnerEmail === newOwnerEmail) { return; } file.removeEditor(newOwnerEmail); var base = 'https://docs.google.com/feeds/'; var fetchArgs = googleOAuth_('docs', base); fetchArgs.method = 'POST'; var rawXml = "&lt;entry xmlns='http://www.w3.org/2005/Atom' xmlns:gAcl='http://schemas.google.com/acl/2007'&gt;" +"&lt;category scheme='http://schemas.google.com/g/2005#kind' " +"term='http://schemas.google.com/acl/2007#accessRule'/&gt;" +"&lt;gAcl:role value='owner'/&gt;" +"&lt;gAcl:scope type='user' value='"+newOwnerEmail+"'/&gt;" +"&lt;/entry&gt;"; fetchArgs.payload = rawXml; fetchArgs.contentType = 'application/atom+xml'; var url = base + encodeURIComponent(oldOwnerEmail) + '/private/full/'+fileOrFolderId+'/acl?v=3&amp;alt=json'; var content = UrlFetchApp.fetch(url, fetchArgs).getContentText(); } //Google oAuth function googleOAuth_(name,scope) { var oAuthConfig = UrlFetchApp.addOAuthService(name); oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope); oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken"); oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken"); oAuthConfig.setConsumerKey("anonymous"); oAuthConfig.setConsumerSecret("anonymous"); return {oAuthServiceName:name, oAuthUseToken:"always"}; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload