Home > Software design >  PowerShell compare two objects and output equals
PowerShell compare two objects and output equals

Time:09-30

I have a text file with different user names inside.

Now I want to get all groups where the users are inside, compare the user and only output the groups where ALL users are inside.

$users = Get-Content -path "C:\users.txt"

foreach($user in $users) 
{
    write-host "Group Membership for: " $user
    Get-ADPrincipalGroupMembership -Identity $user | Select name 
}

CodePudding user response:

If the user list is not huge, the following is a simple way to group all groups that are common among the users:

$users = Get-Content -path "C:\users.txt"
$users | Foreach-Object {
    # Grouping groups based on distinguishedName
    # List groups that appear as many times as the number of users
    Get-ADPrincipalGroupMembership -Identity $_
} | Group-Object DistinguishedName | Where {$_.Count -eq $users.Count} |
    Select-Object @{n='Name';e={$_.Group[0].Name}}
  • Related