Home > Mobile >  Get AD group members with ADSI - Powershell
Get AD group members with ADSI - Powershell

Time:04-27

I cannot use the Active Directory Module to get the SamAccountName of the users in a specific AD-group. How can I do this with ADSI?

I've tried:

$Group = [ADSI]"LDAP://DN of the AD group"
$Group.Member | ForEach-Object {
    $Searcher = [adsisearcher]"(samAccountName=$_)"
    $searcher.FindOne().Properties
}

But I see this message:

The samAccountName search filter is invalid.

How can I do this?

CodePudding user response:

There are 2 ways around this as I see it, there might be an easier way of doing it though.

One is to search for all users which's memberOf attribute has the DistinguishedName of the group (this might be the less cumbersome approach):

$group = 'CN=myGroup, OU=myOU, DC=myDomain'
$searcher = [adsisearcher]"(&(objectclass=user)(objectcategory=person)(memberof=$group))"
$members = foreach($member in $searcher.FindAll()) {
    $member.Properties.samaccountname
}

The other way around is using the same approach as you're using in your question:

$group = 'CN=myGroup, OU=myOU, DC=myDomain'
$adsi = [adsi]"LDAP://$group"
$members = foreach($member in $adsi.member) {
    $isUser = [adsi]"LDAP://$member"
    if('person' -in $isUser.objectclass) {
        $isUser.samaccountname
    }
}

Similar as the one above, but using adsisearcher, not sure which one would be more efficient in this case:

$members = foreach($member in $adsi.member) {
    $check = [adsisearcher]"(&(distinguishedname=$member)(objectclass=user)(objectcategory=person))"
    if($isUser = $check.FindOne()) {
        $isUser.Properties.samaccountname
    }
}

CodePudding user response:

I ran this modified version of your code on my own system, so I could see what the search string actually looked like:

$Group = [ADSI]"LDAP://DN of the AD group"
$Group.Member | ForEach-Object {
    $searchKey = "(samAccountName=$_)"
    $searchKey
    $Searcher = [adsisearcher]$searchKey 
    # $searcher.FindOne().Properties
}

Note the point where I let $searchKey come to the console. When I do this, I see values with the full distinguished name instead of just samAccountName. Based on this result I changed the code to look for that value instead of samAccountName, and then I saw (presumably) expected results:

$Group = [ADSI]"LDAP://DN of the AD group"
$Group.Member | ForEach-Object {
    $Searcher = [adsisearcher]"(distinguishedName=$_)"
    $searcher.FindOne().Properties
}
  • Related