Admin SDK 報表服務

Admin SDK 報表服務可讓您在 Apps Script 中使用 Admin SDK 的 Reports API。這個 API 可讓 Google Workspace 網域 (包括轉售商) 的管理員為自己的網域建立自訂用量報表。

參考資料

如要進一步瞭解這項服務,請參閱 Admin SDK Reports API 的參考文件。與 Apps Script 中的所有進階服務一樣,Admin SDK Reports 服務會使用與公開 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;
  }, {});
}