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

如何向自定义属性customSchema添加数据?Google Apps Script求助

正确向Google Workspace用户自定义Schema写入数据的方法

正确实现代码

方法1:使用patch更新(推荐,仅修改必要字段)

function copyBuildingIdToSiteCode(userEmail) {
  // 获取用户完整信息
  var user = AdminDirectory.Users.get(userEmail, { projection: 'full' });
  
  // 确保customSchemas及目标Schema、字段的层级存在
  var customSchemas = user.customSchemas || {};
  // 初始化Employee_Information结构(如果不存在)
  if (!customSchemas.Employee_Information) {
    customSchemas.Employee_Information = {};
  }
  // 赋值默认字段的值到自定义字段,兼容locations为空的情况
  customSchemas.Employee_Information.Site_Code = user.locations[0]?.buildingId || '';
  
  // 使用patch仅更新customSchemas部分,避免覆盖其他用户数据
  AdminDirectory.Users.patch({ customSchemas: customSchemas }, userEmail);
}

方法2:使用update更新(需处理完整用户对象)

function copyBuildingIdToSiteCodeUpdate(userEmail) {
  var user = AdminDirectory.Users.get(userEmail, { projection: 'full' });
  
  // 初始化层级结构,防止属性不存在报错
  if (!user.customSchemas) user.customSchemas = {};
  if (!user.customSchemas.Employee_Information) {
    user.customSchemas.Employee_Information = {};
  }
  
  user.customSchemas.Employee_Information.Site_Code = user.locations[0]?.buildingId || '';
  
  // 更新完整用户对象
  AdminDirectory.Users.update(user, userEmail);
}

你之前尝试的错误分析

  • 初始尝试:直接访问user.customSchemas.Employee_Information.Site_Code时,若Employee_Information不存在会触发属性不存在的错误,进而导致API调用失败,必须先检查并初始化层级结构。
  • 尝试A:AdminDirectory.Schemas.insert是域级操作,用于在整个Google Workspace域中创建自定义Schema,第二个参数需传入你的域名(如yourdomain.com)而非用户邮箱;且你已在管理控制台创建Schema,无需再调用此接口。
  • 尝试B:格式错误——Site_Code是单值字符串字段,无需用数组包裹{value: ..., type: ...}结构,直接赋值字符串即可;同时Schema名称写错为User_Information,与目标Employee_Information不符。
  • 尝试C:变量名拼写错误(customSchemas写成customSchema),且误解了Schema创建逻辑——用户级无法创建Schema,Schema是域级资源,仅能在Admin控制台或通过域级Schemas.insert创建,用户仅能写入已存在的Schema字段。

内容的提问来源于stack exchange,提问作者Kyle K.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 22:46:12