Search
Clear search
Close search
Google apps
Main menu
true

Rename users in large organizations

When you have 50 or more users in your organization, you can use the Directory API to rename those users after you change your primary domain. To do this, you must sign in the Admin console as a super administrator and enable API access. For more information, see Administrative APIs.

Tip: You can expect this process to take anywhere from 6 minutes for 240 users to as many as 10 hours for 24,000 users.

1. Export a list of users to Google Sheets
  1. Sign in to your Google Admin console.

    Sign in using your administrator account (does not end in @gmail.com).

  2. From the Admin console dashboard, go to Users.
  3. In the top-right corner, click More More  and select Download users.
  4. Select Download all users, check Create a Google spreadsheet, and click OK.
  5. On the Download list of users pop-up, click Open to view the generated spreadsheet.

Important: Remove any users from the spreadsheet that shouldn't be renamed, including the one with which you signed in.

2. Create  a new project in the Script editor
  1. On the spreadsheet's menu bar, click Tools > Script editor.
  2. Under the Code.gs tab, copy and paste the following code replacing the 
    entire content of the code file:

    Code to put under the Code.gs tab.

    // Cell Colors
    COLOR_GRAY = '#434343';
    COLOR_GREEN = '#B5D5A7';
    COLOR_RED = '#E89898';
    COLOR_YELLOW = '#FDE398';
    COLOR_WHITE = '#FFFFFF';

    // Sheet Columns
    COLUMN_PARAMETER = 1;
    COLUMN_RESULT = 2;
    COLUMN_USER = 1;
    COLUMN_VALUE = 2;

    // Header Labels
    HEADER_PARAMETER = 'Parameter';
    HEADER_RESULT = 'Result';
    HEADER_USER = 'Username';
    HEADER_VALUE = 'Value';

    // Status Messages
    MESSAGE_COMPLETE = 'User renamed to: ';
    MESSAGE_PAUSE = 'Select "Start Rename" from the "Actions" menu to continue';
    MESSAGE_RUNTIME = 'Runtime exceeded. Will resume automatically in a few minutes';
    MESSAGE_STOP = 'Select "Start Rename" from the "Actions" menu to continue';

    // Parameter Labels
    PARAMETER_DOMAIN = 'Domain Name';
    PARAMETER_CURRENT = 'Current Row';
    PARAMETER_RUN = 'Run Number';

    // Parameter Dimensions
    PARAMETER_COLUMNS = 2;
    PARAMETER_ROWS = 4;

    // Result Dimensions
    RESULT_COLUMNS = 2;

    // Sheet Rows
    ROW_DOMAIN = 2;
    ROW_HEADER = 1;
    ROW_CURRENT = 4;
    ROW_RUN = 3;

    // Runtime Settings
    RUNTIME_MAX = 270000;
    RUNTIME_PAUSE = 60000;

    // Sheet Names
    SHEET_PARAMETERS = 'Parameters';
    SHEET_RESULTS = 'Results';

    // Status Labels
    STATUS_ABORT = '[ABORTED]';
    STATUS_ERROR = '[ERROR]';
    STATUS_PAUSE = '[PAUSED]';
    STATUS_COMPLETE = '[COMPLETED]';

    // Cell Sizes
    WIDTH_SMALL = 200;
    WIDTH_MEDIUM = 400;
    WIDTH_LARGE = 800;

    // Parameter Values
    VALUE_CURRENT = 2;
    VALUE_NULL = '';
    VALUE_RUN = 1;

    // Clears all triggers from current project.
    function clearTriggers() {
      var triggers = ScriptApp.getProjectTriggers();
      for (var i in triggers) {
        ScriptApp.deleteTrigger(triggers[i]);
      }
    }

    // Returns currently active sheet
    function getCurrentSheet() {
      return SpreadsheetApp.getActiveSheet();
    }

    // Returns currently active spreadsheet
    function getCurrentSpreadsheet() {
      return SpreadsheetApp.getActiveSpreadsheet();
    }

    // Returns value of specified cell in a sheet
    function getCellValue(sheet, row, column) {
      return sheet.getRange(row, column).getValue();
    }

    // Returns value of the specified parameter
    function getParameter(parameter) {
      return getCellValue(getSheet(SHEET_PARAMETERS), parameter, COLUMN_VALUE);
    }

    // Returns sheet with the specified name (if one exists)
    function getSheet(name) {
      return getCurrentSpreadsheet().getSheetByName(name);
    }

    // Returns true if 'haystack' contains 'needle'.
    function hasString(haystack, needle) {
      return String(haystack).indexOf(needle) != -1;
    }

    // Returns true if script is nearing the max run time (4.5 min).
    function isRuntimeExpired(start, currentTime) {
      return currentTime - start >= RUNTIME_MAX;
    }

    // Adds custom items to "Actions" menu of spreadsheet
    function onOpen() {
      var ui = SpreadsheetApp.getUi();
      ui.createMenu('Actions')
        .addItem('Start Rename', 'startRename')
        .addItem('Pause Rename', 'pauseRename')
        .addItem('Stop Rename', 'stopRename')
        .addItem('Reset Spreadsheet', 'resetSpreadsheet')
        .addToUi();
    }

    // Pause rename process (manually)
    function pauseRename() {
      clearTriggers();
      var results = getSheet(SHEET_RESULTS);
      var lastRow = results.getLastRow();
      var row = getParameter(ROW_CURRENT);
      var currentResult = getCellValue(results, row, COLUMN_RESULT);
      if (!hasString(currentResult, STATUS_ABORT) &&
        !hasString(currentResult, STATUS_ERROR) &&
        !hasString(currentResult, STATUS_PAUSE)) {
        row = row + 1;
      }
      if (row < lastRow) {
        setResult(row, COLOR_YELLOW, STATUS_PAUSE, MESSAGE_PAUSE);
      }
    }

    // Formats layout of "Parameters" sheet
    function formatParameters() {
      var parameters = getSheet(SHEET_PARAMETERS);
      var lastColumn = parameters.getMaxColumns();
      var lastRow = parameters.getMaxRows();
      if (lastColumn > PARAMETER_COLUMNS) {
        parameters.deleteColumns(
        PARAMETER_COLUMNS + 1, lastColumn - PARAMETER_COLUMNS);
      }
      parameters.getRange(ROW_HEADER, COLUMN_PARAMETER, lastRow).clear();
      parameters.getRange(ROW_HEADER, COLUMN_VALUE, lastRow).clear();
      parameters.getRange(ROW_HEADER, COLUMN_RESULT).setFontColor(COLOR_WHITE);
      parameters.setColumnWidth(COLUMN_PARAMETER, WIDTH_SMALL);
      parameters.setColumnWidth(COLUMN_VALUE, WIDTH_SMALL);
      parameters.getRange(ROW_HEADER, COLUMN_PARAMETER)
        .setBackground(COLOR_GRAY)
        .setFontColor(COLOR_WHITE)
        .setValue(HEADER_PARAMETER);
      parameters.getRange(ROW_HEADER, COLUMN_VALUE)
        .setBackground(COLOR_GRAY)
        .setFontColor(COLOR_WHITE)
        .setValue(HEADER_VALUE);
      parameters.getRange(ROW_DOMAIN, COLUMN_PARAMETER).setValue(PARAMETER_DOMAIN);
      parameters.getRange(ROW_RUN, COLUMN_PARAMETER).setValue(PARAMETER_RUN);
      parameters.getRange(ROW_CURRENT, COLUMN_PARAMETER)
        .setValue(PARAMETER_CURRENT);
      parameters.setFrozenRows(ROW_HEADER);
    }

    // Formats layout of "Results" sheet
    function formatResults() {
      var results = getSheet(SHEET_RESULTS);
      var userHeader = results.getRange(ROW_HEADER, COLUMN_USER);
      var lastColumn = results.getMaxColumns();
      var lastRow = results.getLastRow();
      if (hasString(userHeader.getValue(), '@')) {
        results.insertRowBefore(1);
      }
      if (lastColumn > RESULT_COLUMNS) {
        results.deleteColumns(RESULT_COLUMNS + 1, lastColumn - RESULT_COLUMNS);
      }
      if (lastColumn < RESULT_COLUMNS) {
        results.insertColumnAfter(COLUMN_USER);
      }
      results.getRange(ROW_HEADER, COLUMN_USER, lastRow).clearFormat();
      results.getRange(ROW_HEADER, COLUMN_RESULT, lastRow).clear();
      userHeader.setFontColor(COLOR_WHITE);
      results.getRange(ROW_HEADER, COLUMN_RESULT).setFontColor(COLOR_WHITE);
      userHeader.setValue(HEADER_USER);
      results.setColumnWidth(COLUMN_USER, WIDTH_MEDIUM);
      results.setColumnWidth(COLUMN_RESULT, WIDTH_LARGE);
      results.setFrozenRows(ROW_HEADER);
      setResult(ROW_HEADER, COLOR_GRAY, HEADER_RESULT, '');
    }

    // Renames email address of each user in "Results" sheet
    function renameUsers(start) {
      var results = getSheet(SHEET_RESULTS);
      SpreadsheetApp.setActiveSheet(results);
      var lastRow = results.getLastRow();
      var firstRow = getParameter(ROW_CURRENT);
      var domain = getParameter(ROW_DOMAIN);
      if (firstRow && firstRow <= lastRow) {
        setResult(firstRow, COLOR_WHITE, VALUE_NULL, VALUE_NULL);
        for (var row = firstRow; row <= lastRow; row++) {
          setCurrentRow(row);
          var currentEmail = getCellValue(results, row, COLUMN_USER);
          var currentResult = getCellValue(results, row, COLUMN_RESULT);
          var userExists = false;
          if (row != lastRow) {
            if (isRuntimeExpired(start, new Date().getTime())) {
              setTrigger(RUNTIME_PAUSE);
              setTrigger(RUNTIME_PAUSE + RUNTIME_MAX);
              setResult(row, COLOR_YELLOW, STATUS_PAUSE, MESSAGE_RUNTIME);
              return;
            }
          }
          if (hasString(currentResult, STATUS_PAUSE)) {
            return;
          }
          if (hasString(currentResult, STATUS_ABORT)) {
            var parameters = getSheet(SHEET_PARAMETERS);
            setCurrentRow(row);
            getCurrentSpreadsheet().deleteSheet(parameters);
            return;
          }
          if (hasString(currentResult, STATUS_COMPLETE)) continue;
          setResult(row, COLOR_RED, STATUS_ABORT, VALUE_NULL);
          if (!hasString(currentEmail, '@')) continue;
          var delimiter = currentEmail.indexOf('@');
          var currentUsername = currentEmail.substring(0, delimiter);
          var newUsername = currentUsername + '@' + domain;
          var user = {'primaryEmail': newUsername};
          try {
            AdminDirectory.Users.update(user, currentEmail);
            message = MESSAGE_COMPLETE + user.primaryEmail;
            setResult(row, COLOR_GREEN, STATUS_COMPLETE, message);
          } catch (err) {
            setResult(row, COLOR_RED, STATUS_ERROR, err.message);
          }
          Utilities.sleep(100);
          parameters = getSheet(SHEET_PARAMETERS);
        }
      }
      getCurrentSpreadsheet().deleteSheet(parameters);
      return;
    }

    //Resets layout of "Results" sheet; removes "Parameters" sheet
    function resetSpreadsheet() {
      clearTriggers();
      var parameters = getSheet(SHEET_PARAMETERS);
      if (parameters) {
        getCurrentSpreadsheet().deleteSheet(parameters);
      }
      formatResults();
    }

    //Sets background color of specified cell in a sheet
    function setCellColor(sheet, row, column, color) {
      sheet.getRange(row, column).setBackground(color);
    }

    //Sets value of specified cell in a sheet
    function setCellValue(sheet, row, column, value) {
      sheet.getRange(row, column).setValue(value);
    }

    //Sets value of "Row Number" parameter
    function setCurrentRow(row) {
      var parameters = getSheet(SHEET_PARAMETERS);
      Utilities.sleep(50);
      setCellValue(parameters, ROW_CURRENT, COLUMN_VALUE, row);
      Utilities.sleep(50);
    }

    //Sets value of "Domain Name" parameter
    function setDomainName(domain) {
      var parameters = getSheet(SHEET_PARAMETERS);
      setCellValue(parameters, ROW_DOMAIN, COLUMN_VALUE, domain);
    }

    //Sets result of specified row in "Results" sheet
    function setResult(row, color, status, message) {
      var results = getSheet(SHEET_RESULTS);
      results.getRange(row, COLUMN_USER).setBackground(color);
      results.getRange(row, COLUMN_RESULT).setBackground(color);
      if (message == VALUE_NULL) {
        results.getRange(row, COLUMN_RESULT).setValue(status);
      } else {
        results.getRange(row, COLUMN_RESULT).setValue(status + ' ' + message);
      }
    }

    //Sets value of "Run Number" parameter
    function setRunNumber(count) {
      var parameters = getSheet(SHEET_PARAMETERS);
      setCellValue(parameters, ROW_RUN, COLUMN_VALUE, count);
    }

    function setTrigger(pause) {
      ScriptApp.newTrigger('startRename').timeBased().after(pause).create();
    }

    //Starts rename process
    function startRename() {
      clearTriggers();
      var start = new Date().getTime();
      if (getSheet(SHEET_PARAMETERS)) {
        var results = getSheet(SHEET_RESULTS);
        var parameters = getSheet(SHEET_PARAMETERS);
        setRunNumber(getParameter(ROW_RUN) + 1);
      } else {
        getCurrentSheet().setName(SHEET_RESULTS);
        formatResults();
        var domains = AdminDirectory.Domains.list('my_customer').domains;
        var ui = SpreadsheetApp.getUi();
        var input = ui.prompt('Rename users to which domain?', ui.ButtonSet.OK_CANCEL);
      if (input.getSelectedButton() == ui.Button.OK) {
        var valid = false;
        var domain = input.getResponseText().toLowerCase();
        for (var i in domains) {
          if (domain == domains[i].domainName.toLowerCase()) {
            valid = true;
          }
        }
        if (!valid) {
          ui.alert(
          'The specified domain is invalid! Please try again.',
          ui.ButtonSet.OK);
          return;
        }
      } else {
        return;
      }
      var results = getSheet(SHEET_RESULTS);
      var parameters = getCurrentSpreadsheet().insertSheet(SHEET_PARAMETERS);
      formatParameters();
      setDomainName(domain);
      setCurrentRow(VALUE_CURRENT);
      setRunNumber(VALUE_RUN);
      }
      renameUsers(start);
    }

    //Stop rename process
    function stopRename() {
      clearTriggers();
      var results = getSheet(SHEET_RESULTS);
      var lastRow = results.getLastRow();
      var row = getParameter(ROW_CURRENT);
      var currentResult = getCellValue(results, row, COLUMN_RESULT);
      if (hasString(currentResult, STATUS_ABORT) ||
        hasString(currentResult, STATUS_ERROR) ||
        hasString(currentResult, STATUS_PAUSE)) {
      var parameters = getSheet(SHEET_PARAMETERS);
      if (parameters) {
        getCurrentSpreadsheet().deleteSheet(parameters);
      }
      } else {
        row = row + 1;
      }
      setResult(row, COLOR_RED, STATUS_ABORT, MESSAGE_STOP);
    }

  3. Click File > Save.
  4. Enter a new project name, such as Rename Users, and click OK.
3. Enable the Admin SDK and Directory API
  1. In your open Script editor, click Resources > Advanced Google services.
  2. Turn on the Admin Directory API service and click the Google Developers Console link.
  3. Under Google Apps APIs, click Admin SDK.
  4. Click Enable.
  5. Close the API Manager tab and return to Script editor.
  6. Click OK to close the Advanced Google Services window.
  7. In the Script editor, select File > Save.
  8. Close the Script editor tab and return to the spreadsheet.
4. Run your new project

When the spreadsheet reloads, an Actions menu should appear next to Help.

  1. In Google Chrome, click View > Reload This Page.
    Users renamed successfully show as [COMPLETED] in the Results column.
  2. In the spreadsheet, click Actions > Start Rename.
  3. If prompted with Authorization required, click Continue.
  4. Click Allow.
    Note: If the script runs successfully, you see "Rename users to which domain?"
  5. Enter the new primary domain and click Ok.

Users renamed successfully show as [COMPLETED] in the Results column.

Was this article helpful?
How can we improve it?
Sign in to your account

Get account-specific help by signing in with your G Suite account email address, or learn how to get started with G Suite.