Admin SDK 报告服务

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

参考

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

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

示例代码

以下示例代码使用该 API 的版本 1

生成登录活动报告

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

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;
  }, {});
}