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

如何使用Graph API实现Office 365用户添加到多个通讯组列表

Graph API 批量添加Office 365用户到多个通讯组实现方案

前置配置

  • 先在Azure AD完成应用注册,生成客户端ID、客户端密钥,记录租户ID
  • 给注册的应用分配应用程序权限:Group.ReadWrite.All、User.Read.All,必须完成管理员权限同意
  • 提前获取待操作的用户UPN(或者用户ID)、目标通讯组的ID列表,通讯组ID可以通过Graph接口查询获取

PowerShell 可运行脚本

先安装依赖模块:
Install-Module Microsoft.Graph -Scope CurrentUser -Force

完整脚本:

# 引入Graph模块
Import-Module Microsoft.Graph.Authentication
Import-Module Microsoft.Graph.Groups

# 替换为自己的配置参数
$tenantId = "你的Azure租户ID"
$clientId = "注册应用的客户端ID"
$clientSecret = "注册应用的客户端密钥"
$targetUserUPN = "待添加的用户UPN,比如zhangsan@contoso.com"
# 替换为目标通讯组ID列表
$targetGroupIds = @(
    "组ID1",
    "组ID2",
    "组ID3"
)

# 应用身份认证
$secSecret = ConvertTo-SecureString $clientSecret -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($clientId, $secSecret)
Connect-MgGraph -TenantId $tenantId -ClientSecretCredential $credential

# 获取用户ID
$userId = (Get-MgUser -UserId $targetUserUPN).Id

# 循环添加到各个通讯组
foreach ($groupId in $targetGroupIds) {
    try {
        New-MgGroupMember -GroupId $groupId -DirectoryObjectId $userId
        Write-Host "成功添加用户到组:$groupId"
    } catch {
        Write-Host "添加到组$groupId失败:" $_.Exception.Message
    }
}

# 断开连接
Disconnect-MgGraph

Python 可运行脚本

先安装依赖包:
pip install msgraph-core azure-identity

完整脚本:

from azure.identity import ClientSecretCredential
from msgraph.core import GraphClient

# 替换为自己的配置参数
tenant_id = "你的Azure租户ID"
client_id = "注册应用的客户端ID"
client_secret = "注册应用的客户端密钥"
target_user_upn = "待添加的用户UPN,比如zhangsan@contoso.com"
# 替换为目标通讯组ID列表
target_group_ids = [
    "组ID1",
    "组ID2",
    "组ID3"
]

# 初始化认证客户端
credential = ClientSecretCredential(
    tenant_id=tenant_id,
    client_id=client_id,
    client_secret=client_secret
)
client = GraphClient(credential=credential, scopes=["https://graph.microsoft.com/.default"])

# 获取用户ID
user_resp = client.get(f"/users/{target_user_upn}")
user_id = user_resp.json()["id"]

# 循环添加到各个通讯组
for group_id in target_group_ids:
    try:
        resp = client.post(
            f"/groups/{group_id}/members/$ref",
            json={"@odata.id": f"https://graph.microsoft.com/v1.0/users/{user_id}"}
        )
        resp.raise_for_status()
        print(f"成功添加用户到组:{group_id}")
    except Exception as e:
        print(f"添加到组{group_id}失败:{str(e)}")

常见问题说明

  • 403权限错误:优先检查应用注册的权限是否为应用程序权限(不是委托权限),是否已经由全局管理员完成同意授权
  • 404找不到资源:确认用户UPN、组ID是否正确,对应对象是否存在于当前租户
  • 节流限制:单次批量操作不要超过20个组,高频调用建议添加1-2秒的间隔避免触发Graph API限流

内容的提问来源于stack exchange,提问作者Allo Jeswin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:48:01