Add-AzureADGroupMember error"执行AddGroupMember时发生错误"

时间:2017-11-15 19:46:11

标签: azure-active-directory azure-powershell

我们在将成员添加到安全组时遇到了一致的错误

refObjectId=Get-AzureRmADUser -UserPrincipalName $UserEmail
Add-AzureADGroupMember -ObjectId [securitygroupID] -RefObjectId $refObjectId.Id
上面的

脚本大约有一半的时间成功,并且失败了大约一半:

  

异常:执行AddGroupMember StatusCode时发生错误:   BadRequest ErrorCode:Request_BadRequest消息:添加了一个或多个   以下已修改的属性已存在对象引用:   '会员'

这个组通常有数百个用户,主要有一个共同的名称(即临时用户)但是唯一的UPN(即user12345 @)我假设当Add-AzureADGroupMember运行时,它首先验证成员是否已存在于组中并且是检查用户名(将有重复)而不是objectid(没有重复)

强制命令使用ObjectID进行验证以防止成员误报的任何建议都已存在?

2 个答案:

答案 0 :(得分:0)

实际上,如果指定的用户已经是组的成员,则发生指定的错误。

关于:

  

关于强制命令使用ObjectID进行验证的任何建议   防止成员的误报已经存在?

可以考虑以下方法:

a)利用Get-AzureADGroupMember cmdlet预先检索 all 个现有成员,例如:

$targetGroup = Get-AzureADGroup -Filter "DisplayName eq '<group name>'"
$groupMembers = Get-AzureADGroupMember -ObjectId $targetGroup.ObjectId -All $true

b)在调用Add-AzureADGroupMember之前验证用户是否属于组:

$targetUser = Get-AzureADUser -Filter "Mail eq '<email>'"
$existingMember =  $groupMembers | Where-Object { $_.ObjectId -eq $targetUser.ObjectId }
if(!$existingMember){
   Add-AzureADGroupMember -ObjectId $targetGroup.ObjectId -RefObjectId $targetUser.ObjectId  
}

答案 1 :(得分:0)

虽然Vadim的回答相当不错,但我提出了一个更小,更简单的解决方案:

# Get the group that we want to modify.
$Group = Get-AzureADGroup -Filter "DisplayName eq 'GroupName'"
# Get all of the group members.
$Members = $Group | Get-AzureADGroupMember -All $true
# Get the user that you want to check
$User = Get-AzureADUser -Filter "Mail eq 'email'"

# Compare the Member list Object IDs with the user's Object ID via the -contains operator. (You don't need .ObjectID, but this could make the function faster in large jobs as you don't need to compare all values, just the one that you know is unique)
$IsUserInGroup = $Members.ObjectID -contains $User.ObjectID

$ IsUserInGroup如果用户在组中,将返回true,否则返回false。要对此进行反转,请执行(-NOT $IsUserInGroup)或使用-notcontains