Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PowerShell Find Members of Two Specific AD Groups

I have AD groups called ADGroup1 and ADGroup2. I know I can see a list of each by querying:

Get-ADGroupMember -Identity "ADGroup1

or

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading