Admin SDK 报告服务

通过 Admin SDK 报告服务,您可以使用 Admin SDK 的 Reports API: Apps 脚本。借助此 API,管理员可以 的 Google Workspace 网域(包括转销商) 能够为其域创建自定义使用情况报告。

参考

有关此服务的详细信息,请参阅 Admin SDK 的参考文档 Reports API。与 Apps 脚本中的所有高级服务一样,Admin SDK 报告 服务使用与公共 API 相同的对象、方法和参数。如需了解详情,请参阅如何确定方法签名

如需报告问题和寻求其他支持,请参阅 Admin SDK 报告支持指南

示例代码

以下示例代码使用的是版本 1 该 API 的高级 API。

生成登录活动报告

此示例生成上周的登录活动报告, 电子表格。该报告包含时间、用户和登录结果。

advanced/adminSDK.gs
/**
 * Generates a login activity report for the last week as a spreadsheet. The
 * report includes the time, user, and login result.
 * @see https://developers.google.com/admin-sdk/reports/reference/rest/v1/activities/list
 */
function generateLoginActivityReport() {
  const now = new Date();
  const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
  const startTime = oneWeekAgo.toISOString();
  const endTime = now.toISOString();

  const rows = [];
  let pageToken;
  let page;
  do {
    page = AdminReports.Activities.list('all', 'login', {
      startTime: startTime,
      endTime: endTime,
      maxResults: 500,
      pageToken: pageToken
    });
    const items = page.items;
    if (items) {
      for (const item of items) {
        const row = [
          new Date(item.id.time),
          item.actor.email,
          item.events[0].name
        ];
        rows.push(row);
      }
    }
    pageToken = page.nextPageToken;
  } while (pageToken);

  if (rows.length === 0) {
    console.log('No results returned.');
    return;
  }
  const spreadsheet = SpreadsheetApp.create('Google Workspace Login Report');
  const sheet = spreadsheet.getActiveSheet();

  // Append the headers.
  const headers = ['Time', 'User', 'Login Result'];
  sheet.appendRow(headers);

  // Append the results.
  sheet.getRange(2, 1, rows.length, headers.length).setValues(rows);

  console.log('Report spreadsheet created: %s', spreadsheet.getUrl());
}

生成用户使用情况报告

此示例生成了上周这一天的用户使用情况报告, 电子表格。该报告包含以下信息:日期、用户、上次登录时间、 收到的电子邮件数,以及拥有的文档数。

advanced/adminSDK.gs
/**
 * Generates a user usage report for this day last week as a spreadsheet. The
 * report includes the date, user, last login time, number of emails received,
 * and number of drive files created.
 * @see https://developers.google.com/admin-sdk/reports/reference/rest/v1/userUsageReport/get
 */
function generateUserUsageReport() {
  const today = new Date();
  const oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
  const timezone = Session.getScriptTimeZone();
  const date = Utilities.formatDate(oneWeekAgo, timezone, 'yyyy-MM-dd');

  const parameters = [
    'accounts:last_login_time',
    'gmail:num_emails_received',
    'drive:num_items_created'
  ];
  const rows = [];
  let pageToken;
  let page;
  do {
    page = AdminReports.UserUsageReport.get('all', date, {
      parameters: parameters.join(','),
      maxResults: 500,
      pageToken: pageToken
    });
    if (page.warnings) {
      for (const warning of page.warnings) {
        console.log(warning.message);
      }
    }
    const reports = page.usageReports;
    if (reports) {
      for (const report of reports) {
        const parameterValues = getParameterValues(report.parameters);
        const row = [
          report.date,
          report.entity.userEmail,
          parameterValues['accounts:last_login_time'],
          parameterValues['gmail:num_emails_received'],
          parameterValues['drive:num_items_created']
        ];
        rows.push(row);
      }
    }
    pageToken = page.nextPageToken;
  } while (pageToken);

  if (rows.length === 0) {
    console.log('No results returned.');
    return;
  }
  const spreadsheet = SpreadsheetApp.create('Google Workspace User Usage Report');
  const sheet = spreadsheet.getActiveSheet();

  // Append the headers.
  const headers = ['Date', 'User', 'Last Login', 'Num Emails Received',
    'Num Drive Files Created'];
  sheet.appendRow(headers);

  // Append the results.
  sheet.getRange(2, 1, rows.length, headers.length).setValues(rows);

  console.log('Report spreadsheet created: %s', spreadsheet.getUrl());
}

/**
 * Gets a map of parameter names to values from an array of parameter objects.
 * @param {Array} parameters An array of parameter objects.
 * @return {Object} A map from parameter names to their values.
 */
function getParameterValues(parameters) {
  return parameters.reduce((result, parameter) => {
    const name = parameter.name;
    let value;
    if (parameter.intValue !== undefined) {
      value = parameter.intValue;
    } else if (parameter.stringValue !== undefined) {
      value = parameter.stringValue;
    } else if (parameter.datetimeValue !== undefined) {
      value = new Date(parameter.datetimeValue);
    } else if (parameter.boolValue !== undefined) {
      value = parameter.boolValue;
    }
    result[name] = value;
    return result;
  }, {});
}