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

跨Azure AD租户同步组的PowerShell脚本报错求助

Azure AD跨租户组同步问题(仅同步组名,跳过已存在组)

需求说明

  • 将源租户(租户A)的云组同步到目标租户(租户B),仅同步组名称,无需同步成员
  • 脚本需定时运行,目标租户中已存在的组直接跳过
  • 已拥有两个租户的全局管理员权限

现有报错

1. Get-AzureADGroup查询报错

Get-AzureADGroup : Error occurred while executing GetGroups 
Code: Request_UnsupportedQuery
Message: Unsupported Query.
RequestId: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
DateTimeStamp: Thu, 06 Jul 2023 02:35:19 GMT
HttpStatusCode: BadRequest
HttpStatusDescription: Bad Request
HttpResponseStatus: Completed
At C:\Users\xxxxx\xxxxxxxx\GroupSync.ps1:14 char:22
+ ... tingGroup = Get-AzureADGroup -Filter "'DisplayName' eq '$groupname.Di ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-AzureADGroup], ApiException
    + FullyQualifiedErrorId : Microsoft.Open.AzureAD16.Client.ApiException,Microsoft.Open.AzureAD16.PowerShell.GetGroup

2. New-AzureADGroup创建组报错

Group 'class Group {
  DeletionTimestamp: 
  ObjectId: xxxxxxxxxxxxxxxxxxxxxxxxxxxx
  ObjectType: Group
  Description:  
  DirSyncEnabled: 
  DisplayName: xxxxxxxxxxxxxxxxxxx
  LastDirSyncTime: 
  Mail: 
  MailEnabled: False
  MailNickName: NotSet
  OnPremisesSecurityIdentifier: 
  ProvisioningErrors: System.Collections.Generic.List`1[Microsoft.Open.AzureAD.Model.ProvisioningError]
  ProxyAddresses: System.Collections.Generic.List`1[System.String]
  SecurityEnabled: True
}
' does not exist. Creating...
New-AzureADGroup : Error occurred while executing NewGroup 
Code: Request_BadRequest
Message: Invalid value specified for property 'displayName' of resource 'Group'.
RequestId: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
DateTimeStamp: Thu, 06 Jul 2023 02:35:20 GMT
Details: PropertyName  - displayName, PropertyErrorCode  - InvalidLength
HttpStatusCode: BadRequest
HttpStatusDescription: Bad Request
HttpResponseStatus: Completed
At C:\Users\xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxGroupSync.ps1:25 char:21
+ ... $newGroup = New-AzureADGroup -DisplayName "$groupName.DisplayName" -D ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-AzureADGroup], ApiException
    + FullyQualifiedErrorId : Microsoft.Open.AzureAD16.Client.ApiException,Microsoft.Open.AzureAD16.PowerShell.NewGroup

3. 创建失败提示

Failed to create group 'class Group {
  DeletionTimestamp: 
  ObjectId: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  ObjectType: Group
  Description:  
  DirSyncEnabled: 
  DisplayName: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  LastDirSyncTime: 
  Mail: 
  MailEnabled: False
  MailNickName: NotSet
  OnPremisesSecurityIdentifier: 
  ProvisioningErrors: System.Collections.Generic.List`1[Microsoft.Open.AzureAD.Model.ProvisioningError]
  ProxyAddresses: System.Collections.Generic.List`1[System.String]
  SecurityEnabled: True
}

原脚本

# Connect to Tenant A
Connect-AzureAD -TenantId xxxxxxxxxxxxxxxxxxx


# Get All Cloud Groups
$groupNames = Get-AzureADGroup -All $true | where-Object {$_.DirSyncEnabled -like ""}
Disconnect-AzureAD

# Connect To 2nd Tenant
Connect-AzureAD -TenantId xxxxxxxxxxxxxxxxxxxxxxxxxxxx

# Loop through each group name and check if it exists
foreach ($groupName in $groupNames) {
    $existingGroup = Get-AzureADGroup -Filter "'DisplayName' eq '$groupname.DisplayName'"

    if ($existingGroup) {
        Write-Host "Group '$groupName' already exists."
    } else {
        Write-Host "Group '$groupName' does not exist. Creating..."
        
        # Create the group using the desired details
        #$groupDescription = "$groupName.Description"
        $groupMailNickname = "NotSet"
        
        $newGroup = New-AzureADGroup -DisplayName "$groupName.DisplayName" -Description "$groupname.Description" -MailNickname $groupMailNickname -SecurityEnabled $true -MailEnabled $false
        
        if ($newGroup) {
            Write-Host "Group '$groupName' created successfully."
        } else {
            Write-Host "Failed to create group '$groupName'."
        }
    }
}
Disconnect-AzureAD

问题分析

  1. Filter查询语法错误:Get-AzureADGroup的Filter参数格式不正确,单引号嵌套和变量引用方式错误,导致Request_UnsupportedQuery报错。
  2. 对象属性引用错误:循环中直接使用$groupName输出的是整个Group对象,而非属性值;"$groupName.DisplayName"这种写法会把对象字符串和属性名拼接,导致displayName值无效(包含整个对象的类信息),触发InvalidLength错误。
  3. 变量大小写不一致:脚本中混用$groupName和$groupname,PowerShell是大小写敏感的,会导致属性引用失败。

修正后的脚本

# 连接源租户(租户A)
Connect-AzureAD -TenantId "xxxxxxxxxxxxxxxxxxx"

# 获取所有云组(排除AD同步过来的组)
$sourceGroups = Get-AzureADGroup -All $true | Where-Object { [string]::IsNullOrEmpty($_.DirSyncEnabled) }
Disconnect-AzureAD

# 连接目标租户(租户B)
Connect-AzureAD -TenantId "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# 遍历源租户的组
foreach ($group in $sourceGroups) {
    # 正确使用Filter查询目标租户是否存在同名组
    $existingGroup = Get-AzureADGroup -Filter "DisplayName eq '@($group.DisplayName)'"

    if ($existingGroup) {
        Write-Host "组 '$($group.DisplayName)' 已存在,跳过。"
    } else {
        Write-Host "组 '$($group.DisplayName)' 不存在,开始创建..."
        
        # 使用正确的属性值创建组,仅同步名称,描述可留空或按需设置
        $newGroupParams = @{
            DisplayName     = $group.DisplayName
            Description     = $group.Description  # 若不需要同步描述可改为空字符串
            MailNickname    = "NotSet"
            SecurityEnabled = $true
            MailEnabled     = $false
        }

        try {
            $newGroup = New-AzureADGroup @newGroupParams
            Write-Host "组 '$($group.DisplayName)' 创建成功。"
        } catch {
            Write-Host "创建组 '$($group.DisplayName)' 失败:$_"
        }
    }
}

Disconnect-AzureAD

定时运行设置

可以通过Windows任务计划程序实现脚本定时执行:

  • 创建新任务,设置触发器(如每日凌晨执行)
  • 操作选择“启动程序”,程序路径选择powershell.exe,添加参数:-ExecutionPolicy Bypass -File "C:\路径\GroupSync.ps1"
  • 确保任务运行账号拥有足够权限,且已预先配置Azure AD的非交互式登录(避免每次手动输入凭据,可使用服务主体或证书登录)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 08:37:06