Google Apps 脚本快速入门

创建向 Directory API 发出请求的 Google Apps 脚本

快速入门介绍了如何设置和运行调用 Google Workspace API 的应用。本快速入门使用一种简化的身份验证方法,该方法适用于测试环境。对于生产环境,我们建议您先了解身份验证和授权,然后再选择适合您应用的访问凭据

在 Apps 脚本中,Google Workspace 快速入门指南使用高级 Google 服务来调用 Google Workspace API 并处理身份验证和授权流程的一些详细信息。

目标

  • 配置环境。
  • 创建并配置脚本。
  • 运行脚本。

前提条件

  • 启用 API 访问权限的 Google Workspace 网域。
  • 相应网域中具有管理员权限的 Google 账号。

  • Google 云端硬盘访问权限

创建脚本

  1. 前往 script.google.com/create,在 Apps 脚本编辑器中创建新脚本。
  2. 将脚本编辑器的内容替换为以下代码:

adminSDK/directory/quickstart.gs
/**
 * Lists users in a Google Workspace domain.
 * @see https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/list
 */
function listUsers() {
  const optionalArgs = {
    customer: "my_customer",
    maxResults: 10,
    orderBy: "email",
  };
  if (!AdminDirectory || !AdminDirectory.Users) {
    throw new Error("Enable the AdminDirectory Advanced Service.");
  }
  const response = AdminDirectory.Users.list(optionalArgs);
  const users = response.users;
  if (!users || users.length === 0) {
    console.log("No users found.");
    return;
  }
  // Print the list of user's full name and email
  console.log("Users:");
  for (const user of users) {
    if (user.primaryEmail) {
      if (user.name?.fullName) {
        console.log("%s (%s)", user.primaryEmail, user.name.fullName);
      } else {
        console.log("%s", user.primaryEmail);
      }
    }
  }
}

  1. 点击“保存”图标
  2. 点击未命名项目,输入 Quickstart,然后点击重命名

配置脚本

启用 Directory API

打开 Apps 脚本项目。

  1. 点击编辑者
  2. 服务旁边,点击“添加服务”图标
  3. 选择 Admin Directory API,然后点击添加

运行示例

在 Apps 脚本编辑器中,点击运行

首次运行该示例时,系统会提示您授权访问:

  1. 点击查看权限
  2. 选择账号。
  3. 点击允许

脚本的执行日志会显示在窗口底部。

后续步骤