Compare Members of a Group using Where-Object not working

I am trying to compare the members of Group A and Group B. Any user in Group A that is not in Group B must be added to Group B. I cannot get the where-object command working

$a= Get-QADGroupMember -Identity 'Group A' -Indirect -Type 'user' -DontUseDefaultIncludedProperties -ldapfilter '(!(userAccountControl:1.2.840.113556.1.4.803:=2))' -SizeLimit 0| Select-Object samaccountname

$b= Get-QADGroupMember -Identity 'Group B' -Indirect -Type 'user' -DontUseDefaultIncludedProperties -SizeLimit 0 | Select-Object samaccountname

$uniqueusers= $a |where-object {$b -notcontains $_}

foreach ($user in $uniqueusers) {Add-QADGroupMember -Identity 'Group B' -Member $user}

I have a Windows Active Directory module version of this script and it works fine, the issue is the where-object line, it does not return any results. I have also tried "$uniqueusers= $a.samaccountname |where {$b.samaccountname -notcontains $psitem}" and it does not work either.

  • I added the .samAccountName to the user object like this and it worked:


    foreach ($user in $uniqueusers) {Add-QADGroupMember -Identity 'Group B' -Member $user.SamAccountName}

  • When I troubleshoot the script line by line, I do the following:

    C:\Users\$a.count

    1500

    C:\Users\$b.count

    1424

    Based from the results above, $uniqueusers.count should be 76. But instead 

    C:\Users\$uniqueusers.count

    1500

    It looks like it is not actually comparing the objects. In the Windows Powershell version of this script, I get the count of the users in $a that are not in B. 

  • Have you looked at Compare-Object?

    This was introduced in PoSh 5 and it might be helpful?

  • Try this:

    Clear-Host
    
    $SourceGroup = "Source"
    $DestinationGroup = "Destination"
    
    $SourceGroupMembers = Get-QADGroupMember -identity $SourceGroup -Indirect -Type "User" -DontUseDefaultIncludedProperties -LdapFilter "(!(userAccountControl:1.2.840.113556.1.4.803:=2))" -SizeLimit 0
    $DestinationGroupMembers = Get-QADGroupMember -identity $DestinationGroup -Indirect -Type "User" -DontUseDefaultIncludedProperties -SizeLimit 0
    
    $Compare = Compare-Object $SourceGroupMembers $DestinationGroupMembers -PassThru -IncludeEqual
    
    #$Compare | Select-Object samAccountName,sideIndicator
    
    Write-Host "Present in $SourceGroup groups, but not in $DestinationGroup Group"
    $InLeft = $Compare |  Where-object {$_.sideIndicator -eq "<="}
    $InLeft.samAccountName
    
    Write-Host "`nPresent in $DestinationGroup group, but not in $SourceGroup groups"
    $InRight = $Compare | Where-object {$_.sideIndicator -eq "=>"}
    $InRight.samAccountName
    
    Write-Host "`nPresent in both $SourceGroup and $DestinationGroup groups"
    $Union = $Compare | Where-object {$_.sideIndicator -eq "=="}
    $Union.samAccountName