Getting AD Group Membership ADSI using PowerShell

Travis M picture Travis M · Jul 27, 2017 · Viewed 14k times · Source

I currently have ADSI code to get the groups a user is a part of:

$searcher = [adsisearcher]"(samaccountname=$env:USERNAME)"
$searcher.FindOne().Properties.memberof
$adgroups = $User -Replace '^cn=([^,]+).+$', '$1'

However, i am wanting to be able to choose a group and see its members. I currently have this code to get their DN and path.

$Group = [ADSI]"LDAP://cn=Test,cn=Test,dc=some,dc=domain,dc=net"
$Members = $Group.Member | ForEach-Object {[ADSI]"LDAP://$_"}

I am wanting to get other attributes if possible (name, etc.). Any help would be appreciated as i have been trying for a bit.

Answer

BenH picture BenH · Jul 27, 2017

You already have both pieces, the first piece is finding the users in the group, the second piece is using the searcher to get properties for the users. Just use distinguishedname as the [adsisearcher] filter.

$Group = [ADSI]"LDAP://cn=Test,cn=Test,dc=some,dc=domain,dc=net"
$Group.Member | ForEach-Object {
    $Searcher = [adsisearcher]"(distinguishedname=$_)"
    $searcher.FindOne().Properties
}