批量更新用户G-suite

时间:2017-02-06 17:43:56

标签: google-apps-script google-api

我即将使用以下代码批量更新g-suite中的多个用户电子邮件域名 - 在此处找到https://support.google.com/a/answer/7068037

    // 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);
}

由于我正在更改域名,我还想更新不同的字段,例如Department ....

有没有最简单的方法来做而不是使用脚本? 我在哪里可以找到用户字段?

此致

Hugo L

1 个答案:

答案 0 :(得分:1)

我为managing G suite user email signatures编写了一个您可能想要查看的脚本。

python set-signatures.py

它允许您使用HTML模板,用户CSV和Google Service Account API为组织中的每个用户设置签名。