I have AD groups called ADGroup1 and ADGroup2. I know I can see a list of each by querying:
Get-ADGroupMember -Identity "ADGroup1
or
Get-ADGroupMember -Identity "ADGroup2
But does anyone have a quick way for me to find all users that belong to both of the groups?
>Solution :
You can get this via LDAP Filtering with some string manipulation to automatically generate the LDAP Filters:
# Create a filter to get all groups in `$groups`
$groups = 'ADGroup1', 'ADGroup2'
$groupFilter = '(|'
$groups | ForEach-Object {
$groupFilter += '(samAccountName={0})' -f $_
}
$groupFilter += ')'
# create a new filter to get all objects "members of" the groups, exclusive
# change to `(|` for inclusive
$memberOfFilter = '(&'
# get the `DistinguishedName` of all groups and build the filter
(Get-ADGroup -LDAPFilter $groupFilter).DistinguishedName |
ForEach-Object { $memberOfFilter += '(memberof={0})' -f $_ }
$memberOfFilter += ')'
# get all objects "members of" all groups in `$groups`
Get-ADObject -LDAPFilter $memberOfFilter