如果用户存在于广告组中,我如何让我的外观跳过?

How do I get my look to skip over if user exist in adgroup?

我尝试了许多不同的方法,但仍然收到如下所示的相同错误消息。有人对此有解决方案吗?

代码:

$RolesCollection = @()
$Roles = Get-MsolRole
ForEach ($Role In $Roles){
  $Members = Get-MsolRoleMember -RoleObjectId $Role.ObjectId
  ForEach ($Member In $Members) {
    $data = New-Object PSObject -Property @{
      MemberObjectID = $Member.ObjectId
    }
    $RolesCollection += $data
  }
#Adds users with admin roles into PIM group via member object ID
      forEach ($user in $RolesCollection){

      #check if the user exists in the AAD Group, if not, add into it.
      $members = Get-AzureADGroupMember -ObjectId $adGroup | Select -ExpandProperty ObjectID


        If ($members -contains $user) {
            
            Write-Output " $user exist in $adgroup"

         } Else {
            Add-AzureADGroupMember -ObjectId $adGroup -RefObjectId $($user.MemberObjectID)
         }

      }
}

这是错误信息:

Add-AzureADGroupMember:执行 AddGroupMember 时出错 代码:Request_BadRequest 消息:一个或多个添加的对象引用已存在,用于以下修改 属性:'members'.

$members 不包括 $user 因为它们的类型不同。

您需要使用 Get-AzureADUser 获取 AAD 用户。

#Adds users with admin roles into PIM group via member object ID
      forEach ($user in $RolesCollection){

      $targetUser = Get-AzureADUser -ObjectId $user.MemberObjectID | Select -ExpandProperty ObjectID

      #check if the user exists in the AAD Group, if not, add into it.
      $members = Get-AzureADGroupMember -ObjectId $adGroup | Select -ExpandProperty ObjectID


        If ($members -contains $targetUser) {
            
            Write-Output " $targetUser exist in $adgroup"

         } Else {
            Add-AzureADGroupMember -ObjectId $adGroup -RefObjectId $($user.MemberObjectID)
         }

      }