Tuesday 7 April 2020

Bulk change ownership of Google Drive items

The following Google Apps Script is designed to bulk transfer ownership of Google Drive files/folders by iterating through them. It gets the current owner and compares that to the new designated owner before making the change. This particular example will retain the previous owner as an editor of the item.

 

Update 08/03/2023

Unfortunately this tool no longer appears to work for Consumer accounts, only Workspace ones, due to changes in a user needing to accept a request to transfer ownership. Stack Overflow page with some further details.

Screenshot of transfer tool requirements
Screenshot of transfer tool requirements

A 'while' loop is used to cycle through and 'getFiles' in the first instance. From here we can get the email address of the current owner:
var currentFileOwner = file.getOwner().getEmail();
Using an 'if' statement we can then look for a match with the current owner specified on the Welcome sheet and if one is found the new owner can be set:
if (currentFileOwner == currentOwner) {
   file.setOwner(newOwner);
}
The process can then be repeated for sub-folders ('getFolders') which at the end we pass this folder ID back into the Function (hence creating a loop).


File Download

Download the Bulk change ownership of Google Drive items here. Please use 'File' > 'Make a copy' for your own version.


46 comments:

  1. What is the format of "Source Folder ID"?

    ReplyDelete
    Replies
    1. Hi Jeffrey

      It's the long string of characters in the Url that Google Drive uses for its ID. For example: https://drive.google.com/drive/folders/THIS PART IS THE ID

      Kind regards
      Phil

      Delete
    2. Thanks, I'll give it a try.

      Delete
  2. I checked it with the spreadsheet but it didn't work for me, then I went to the script editor, leaving the data in the spreadsheet and it worked without problems
    Thanks friend, I was looking for a solution to a code that I have for a long time but it stopped me with a time limit error

    ReplyDelete
    Replies
    1. Hi

      I've double checked the sheet/script and all seems to be fine. It won't run the very first time you authorise against your Google account (as Google makes you click to run it again as a security measure).

      Thank you for the feedback.

      Kind regards
      Phil

      Delete
    2. I ran into that same "Exceeded maximum execution time" error. If you've got so many files that it takes longer than 6 minutes, you'll need to try one of these strategies: https://stackoverflow.com/questions/14450819/google-app-script-timeout-5-minutes

      Delete
    3. Hi

      Yes you are correct about the limits (https://developers.google.com/apps-script/guides/services/quotas) at the time of developing this it was a small number of items and we had 30 minutes for execution.

      Kind regards
      Phil

      Delete
  3. Here's a script that takes into consideration the 6-minute time limit. It saves a continuationToken so you can start back up where you left off.

    https://stackoverflow.com/a/54104948

    Here's my adaptation of the bulk change script using the continuation token: https://gist.github.com/TurekBot/6da5acd27f92c86dc68d3f6588eeb499

    ReplyDelete
    Replies
    1. Cool, thanks for sharing.

      Kind regards
      Phil

      Delete
    2. How do you add that adaptation into the Google Sheets already made? Sorry, I am very inexperienced with using code.

      Delete
    3. Hi

      You would need to use the Apps Script Editor. Here is the Google site to get started with learning Apps Script: https://developers.google.com/apps-script

      Kind regards
      Phil

      Delete
    4. Thank you for sharing! Does this update still show the pop for current file permission change? How will one know it is running and completed the task?

      Delete
    5. Hi Shawn, yes this uses Toast notifications to tell you the file it is working on and when the permission is changed.

      Delete
  4. Hi, does this only work for google files? I am trying to change ownership for a folder of JPGs and it fails at the line to to set new owner.

    ReplyDelete
    Replies
    1. Hi

      No, I've just tested it on a folder of JPGs and it worked perfectly fine.

      Kind regards
      Phil

      Delete
  5. Hi there, thanks for the script! It doesn't seem to work with jpg. How did you make it work @phil?

    ReplyDelete
    Replies
    1. Hi

      You're welcome.

      As mentioned above it works fine for me with JPGs. The only time I've not seen it work (in general) is when changing the owner to an account that belongs to another domain (eg a business).

      Kind regards
      Phil

      Delete
  6. Hello, Exactly the script I am looking for, however I've made a copy and tried to run it and after giving authorization, I am given the following:

    This app is blocked.
    This app tried to access sensitive info in your Google Account. To keep your account safe, Google blocked this access.

    Trying to change ownership of files from one Google Account to Another (both are no GSuite and just basic Google Accounts).

    Thoughts?

    ReplyDelete
    Replies
    1. Hi Mike

      I'm afraid this is not something I've come across - there are quite a few downloads of this tool. You're not signed into more than 1 Google account at the same time are you, which may be creating some confusion?

      How far do you actually get, to the point where you select your account and see the permissions it requires?

      Are you able to try the steps with another tool on the blog to see if it's just specific to this one?

      Kind regards
      Phil

      Delete
  7. Hi Phil,

    Im looking for something where I can change the current file owner to a different owner. can you help me with the piece of code.Thanks

    ReplyDelete
  8. but I don't want to give any details in the sheet, I will provide those details in the script

    var id = SpreadsheetApp.openById("1QoBtPq4o25Aw1MfgKFFbSSm4miAzYgd-nRB7MKJGy0g");

    var files = DriveApp.getFileById(id)
    var owner = files.getOwner().getEmail();
    Logger.log('owner: ' + owner);

    if (owner != 'abc.com') {
    files.setOwner('abc.com');
    Logger.log('File that was changed: ' + files);

    }

    ReplyDelete
    Replies
    1. Ok, well it looks like you have the code there that you need.

      Kind regards
      Phil

      Delete
  9. FYI this appears to not work for transferring between gmail accounts, nor for some kinds of file types. For src and dest gmail accounts, the file.setOwner call fails with "Access denied: DriveApp.". https://issuetracker.google.com/issues/228826345?pli=1 "won't fix: Following up here, this is the expected behavior as currently Drive does not support the changing of the ownership for items which are owned by gmail.com accounts."

    Also, for PDF files/etc you'll get "Exception: Action not allowed"
    (this person saw the same issue: https://coderanch.com/t/749309/languages/Google-App-Script-setOwner-Fails)

    ReplyDelete
    Replies
    1. Hi Ben

      Ah thanks for the information - we do use it internally on our domain. I see transferring ownership manually in Google Drive itself also prevents the action from occurring between gmail.com accounts.

      That's weird re PDFs - as I've just been able to change 5 of them in a test folder I had (again on our domain).

      Kind regards
      Phil

      Delete
    2. That's correct @Ben, this is a better and more comprehensive description of my comment above where I was wondering why I can't transfer jpegs. I am trying to transfer ownership between gmail.com accounts. When I last tried (in January) I was able to move Workspace files (Sheet, Slides etc) but it doesn't work anymore, like you said. Is there any other way to transfer ownership of several files between two gmail accounts?

      Delete
    3. > Is there any other way to transfer ownership of several files between two gmail accounts

      I've been at this problem many times over the years, and no - there is no means built in to Google Drive/etc to transfer content between gmail accounts in in bulk, only one at a time via the individual file's sharing options. It would appear Google intentionally neuters this functionality as a distinction for their business products.
      The only approach that works but still with significant limitations is to use Google Takeout: download everything and re-upload it to the other account. That works fine for non-Google Docs files, but Docs/Sheets/etc files will get exported in an alternative format, e.g. MS Word, Excel, etc.

      Delete
    4. Thanks for the feedback. That makes sense. I think for my use case the only solution is to use a Business account.

      Delete
  10. Hi Phil,

    I've used your script successfully in the past, but now I'm getting this error when attempting to change ownership:

    Exception: Unexpected error while getting the method or property getFolderById on object DriveApp.

    Any chance you've seen this before and have a workaround?

    Cheers

    ReplyDelete
    Replies
    1. Hi

      Yes I have seen that before, when the Source Folder ID has not been entered correctly into the Sheet. Please make sure you are only entering the Folder ID (not the entire URL). Maybe try making a fresh copy of my Google Sheet file first.

      Kind regards
      Phil

      Delete
  11. We want to transfer Folder ownership from personal Gmail account to business account. But it did not worked .Any help

    ReplyDelete
    Replies
    1. Hi Shripad

      This is not something Google currently supports in general I'm afraid.

      Thanks

      Delete
  12. The script doesnt work anymore as I found in StackOverflow, now the prospective new owner needs to accept the transfer request. The line with file.setOwner(newOwner); throws a silent error that can only be seen in AppScript depuration Problem with file: Exception: Access denied: DriveApp. https://stackoverflow.com/questions/71743249/previously-working-google-app-script-now-produces-permission-error

    ReplyDelete
    Replies
    1. Hi

      Thank you for getting in touch and informing me of this. I will update the post to state it only works for Workspace accounts and not Consumer ones, so others are not caught out.

      Kind regards

      Delete
  13. Is it possible to edit Microsoft files and PDF with the script and transfer ownership?

    ReplyDelete
    Replies
    1. Hi Joe

      The tool is for transferring ownership, not editing files. Yes it will work with Microsoft and PDFs.

      Kind regards

      Delete
  14. Thank you for setting up the Google Sheet to automate the bulk ownership transfer. I have set this up but I am not seeing any change of ownership of the files. Does this work for shared folders?

    I have this setup for an account called examofficer@ which has a single shared folder and the resources are then shared out to several other accounts (exam1234.xx) and so on.

    I have pasted in the folder ID of the shared folder and added the required email addresses - when I run the script it seems to be okay - no errors

    When I refresh and check the files the owner status hasn't changed.

    I am hoping to automate this once I have got the initial part working.

    The accounts are Google Educational ones and not free / consumer ones.

    Many thanks,

    Trevor.

    ReplyDelete
    Replies
    1. Hi Trevor

      Thank you.

      I've just tested the tool again myself and it seems to be working fine (Education Plus).
      What I tried: Bob has a folder called 'Attendance' which is shared with Ted. Inside this folder is a Google Doc called 'Report' shared with Ted and also Alice, along with a Google Sheet called 'Register' not shared with anyone other than Ted. I ran the tool on the 'Attendance' folder ID to change ownership of the files to Alice and it worked.

      You're not logged into more than 1 Google Account when running the tool are you (try an Incognito window if you are unsure).

      Kind regards
      Phil

      Delete
    2. Hi Phil

      Thanks for the quick response. I did try an incognito window but still no joy. No idea what I am doing wrong as you've made the tool so user friendly. I see the small display prompts at the bottom right of the Google sheet as it works through the files - but when I check them - the owner status remains the same. Is there a final message / prompt when it has completed the changes?

      I created a new test folder from the examofficer@ account and shared to the examxxxx account. I then logged into the examxxxx account and uploaded some test files into the new shared area and then used your tool entering the relevant folder ID and the current owner and new owner.

      I'll try it again later on a different setup.

      This idea I am working on is within a school who are planning on using Chromebooks for exams and assessments. The devices are locked down and meet exam regs - I am just trying to simplify the process for the exam officer. I already have an app script which will review the files in a folder and if they are XX days old it will put them in the trash. However - unless I can change the file ownership to the examofficer@ the script can't delete them.

      Once the student has completed the work (usually a google doc) an invigilator will then print the document and the file can then be trashed. It's quite important that the students don't have access to any of their previous files.

      I am sure there are better ways of doing this - but I am keen to help the school with the idea of using chromebooks for exams rather than windows laptops.

      The setup of the single 'master' examofficer@ account is try and make this a single and central account to manage all of the students exam folders - as we don't really want to have to manage each and every student account / folder.

      Sorry for the backstory - just wanted to give you a quick explanation of why I am trying to use your very handy tool to sort the ownership out

      Trevor.

      Delete
    3. Hi Trevor

      Thank you for providing the detail, it's useful to understand the scenario a bit more.

      I built the tool a couple of years ago now so there is no final popup message, just the toasts popping up at the bottom right that you can see.

      I'm a bit stuck as to what the issue may be. I assume you can perform the process you describe manually - so transferring ownership from the examxxxx account to another? What is the 'another'? Is it back to the examofficer@ account?

      Are you trying to change ownership to a completely new account that does not have access to the folder/files in the first instance?

      Kind regards
      Phil

      Delete
  15. Hi Phil,

    I looking for a app script for transfer ownership of a particular google sheet. we have added this script but it transfer all the files in that drive but we need just transfer 1 particular file. Below is the script that we used kindly please advice.

    function ChangeFileOwnership() {

    var new_owner = 'email id';
    //var folderID = cwd().getId();
    var folder = SpreadsheetApp.getActiveSheet();
    var files = folder.getFiles();
    console.log("Folder Owner: "+folder.getOwner().getEmail());
    var search = '"me" in owners';
    var files = folder.searchFiles(search);

    while (files.hasNext()) {
    var file = files.next();
    var file_name = file.getName();
    Logger.log("Changing ownership of " + file_name + "to" + new_owner);
    try{
    file.addEditor(new_owner);
    Logger.log(new_owner + " is now an editor of "+ files_name);
    }
    catch(err){
    Logger.log(err.message);
    }
    try{
    file.setOwner(new_owner);
    }
    catch(err){
    Logger.log(err.message);
    }
    }

    }

    ReplyDelete
    Replies
    1. Hi

      How are you identifying the particular Google Sheet that needs its ownership transferring? Is the user inputting it's ID somewhere? Does it have a particular name? Are you wanting to be able to run the tool multiple times going forwards and always target just one Google Sheet?

      Changing ownership is largely:
      var file = DriveApp.getFileByID('enter file ID here');
      file.setOwner('new owner email address');

      Ta
      Phil

      Delete
  16. Hi Phil

    Thanks for your script. For some reason, it doesn't transfer ownership of the parent folder?

    ReplyDelete
    Replies
    1. Hi Tola

      That is correct, it doesn't have a bit of code for the parent folder. It was needed at the time this was developed for a project.

      Ta

      Delete
  17. Hi Phil,
    I'm using the script i workspace account, on a folder that I don't own, but only works for files or folders( within that folder), that I own to transfer ownership to another user.It's meant to work that way?

    ReplyDelete
    Replies
    1. Hi

      Correct, Google will not allow you to transfer ownership to another named-account if you are not the owner in the first instance.

      Delete