You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Google Script按部门创建多用户并添加至共享Google Drive

解决Google Script无法将用户添加到共享Google Drive的问题

问题背景

需要通过Google Script批量创建用户,并根据部门将用户添加到对应共享Google Drive。用户信息(部门、用户名、密码)存储在Google表格的「User Data」工作表,群组、Drive ID及权限配置存储在「Configuration」工作表。现有脚本可完成用户创建和群组添加操作,但无法实现Drive权限分配。

可能的故障原因

  1. Drive API未启用:脚本依赖Drive.Permissions.insert方法,需手动启用Drive API服务。
  2. 执行账号权限不足:执行脚本的账号需同时拥有Google Workspace管理员权限(创建用户)和目标共享Drive的组织者权限(分配Drive权限)。
  3. 配置数据格式错误:「Configuration」工作表中Drive ID为空或角色值不合法,导致权限分配失败。

修复后的完整脚本

function createUserAndAssignRoles() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet();
  const userSheet = sheet.getSheetByName("User Data");
  const configSheet = sheet.getSheetByName("Configuration");

  if (!userSheet || !configSheet) {
    Logger.log("错误:找不到指定的工作表,请检查工作表名称是否正确");
    return;
  }

  const users = userSheet.getDataRange().getValues();
  const configData = configSheet.getDataRange().getValues();

  const teamGroups = {};
  const teamDrives = {};
  const teamDriveRoles = {};
  const locationGroups = {};

  // 解析配置数据
  configData.forEach((row, index) => {
    // 跳过表头行
    if (index === 0) return;
    const type = row[0]?.trim();
    const name = row[1]?.trim();
    const groupEmails = row[2] ? row[2].split(',').map(e => e.trim()).filter(e => e) : [];
    const driveId = row[3]?.trim();
    const driveRole = row[4]?.trim();

    if (!type || !name) {
      Logger.log(`配置表第${index+1}行数据无效:Type或Name为空`);
      return;
    }

    if (type === 'Team') {
      teamGroups[name] = [...(teamGroups[name] || []), ...groupEmails];
      if (driveId) {
        teamDrives[name] = [...(teamDrives[name] || []), driveId];
        teamDriveRoles[name] = [...(teamDriveRoles[name] || []), driveRole || 'reader'];
      }
    } else if (type === 'Location') {
      locationGroups[name] = [...(locationGroups[name] || []), ...groupEmails];
    } else {
      Logger.log(`配置表第${index+1}行Type无效:${type}`);
    }
  });

  // 处理用户数据
  for (let i = 1; i < users.length; i++) {
    const row = users[i];
    const firstName = row[0]?.trim();
    const lastName = row[1]?.trim();
    const email = row[2]?.trim();
    const password = row[3]?.trim();
    const team = row[4]?.trim();
    const location = row[5]?.trim();

    if (!firstName || !lastName || !email || !password) {
      Logger.log(`用户表第${i+1}行数据无效:必填字段为空`);
      continue;
    }

    // 创建用户
    createGoogleUser(email, firstName, lastName, password);

    // 添加到部门群组
    if (team && teamGroups[team]) {
      teamGroups[team].forEach(groupEmail => {
        addUserToGroup(email, groupEmail);
      });
    }

    // 添加到共享Drive
    if (team && teamDrives[team] && teamDriveRoles[team]) {
      teamDrives[team].forEach((driveId, index) => {
        const role = teamDriveRoles[team][index];
        addUserToDrive(email, driveId, role);
      });
    }

    // 添加到地区群组
    if (location && locationGroups[location]) {
      locationGroups[location].forEach(groupEmail => {
        addUserToGroup(email, groupEmail);
      });
    }
  }
}

function createGoogleUser(email, firstName, lastName, password) {
  try {
    AdminDirectory.Users.insert({
      primaryEmail: email,
      name: { givenName: firstName, familyName: lastName },
      password: password,
      orgUnitPath: "/",
      changePasswordAtNextLogin: false
    });
    Logger.log(`用户创建成功:${email}`);
  } catch (error) {
    Logger.log(`用户创建失败 ${email}:${error.message}`);
  }
}

function addUserToGroup(email, groupEmail) {
  try {
    AdminDirectory.Members.insert({
      email: email,
      role: 'MEMBER'
    }, groupEmail);
    Logger.log(`用户已添加到群组:${groupEmail}`);
  } catch (error) {
    Logger.log(`添加用户到群组失败 ${groupEmail}:${error.message}`);
  }
}

function addUserToDrive(email, driveId, role) {
  try {
    const validRoles = ['reader', 'writer', 'commenter', 'fileOrganizer', 'organizer'];
    let normalizedRole = role.trim().toLowerCase();
    
    // 统一角色别名
    if (normalizedRole === 'viewer') normalizedRole = 'reader';
    // 验证角色合法性
    if (!validRoles.includes(normalizedRole)) {
      Logger.log(`Drive ${driveId}的角色${role}无效,默认使用reader`);
      normalizedRole = 'reader';
    }

    Drive.Permissions.insert({
      type: 'user',
      role: normalizedRole,
      emailAddress: email
    }, driveId, {
      sendNotificationEmail: false,
      supportsAllDrives: true
    });

    Logger.log(`用户已添加到Drive ${driveId},角色:${normalizedRole}`);
  } catch (error) {
    Logger.log(`添加用户到Drive ${driveId}失败:${error.message}`);
  }
}

关键修复点

  1. 增加数据校验:对工作表存在性、配置数据和用户数据的必填字段进行校验,避免空值导致的错误。
  2. 优化配置解析逻辑:跳过表头行,过滤空的群组邮箱,确保Drive角色默认值正确。
  3. 增强错误日志:更详细的错误提示,便于定位问题。

操作步骤

  1. 启用Drive API:
    • 打开脚本编辑器,点击「扩展」→「Apps Script」。
    • 在脚本编辑器中,点击「服务」→「添加服务」,找到「Drive API」并启用。
    • 同时需确保Google Cloud Console中对应项目的Drive API已启用(可通过脚本编辑器的「项目设置」→「Google Cloud项目」跳转查看)。
  2. 验证权限:执行脚本的账号需为Google Workspace管理员,且对目标共享Drive拥有组织者权限。
  3. 检查表格格式:
    • 「User Data」表头:FirstName, LastName, Email, Password, Team, Location
    • 「Configuration」表头:Type, Name, GroupEmails, DriveID, DriveRole,其中Type只能是Team或Location,GroupEmails支持多邮箱逗号分隔,DriveRole可填reader/writer/commenter/fileOrganizer/organizer(viewer会自动转为reader)。

内容的提问来源于stack exchange,提问作者Oleg Adamyuk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 02:14:51