Wednesday, June 09, 2010

Enumerting the members of a nested group with ADSI and powershell

Its often useful with scripts and applications to be able to use Group membership to control what users are affected by a particular application or script. Enumerating nested group members in powershell seems to be a bit of art and there are few different approaches none of which i particular liked so i came up with my own. The following approach uses two hash tables to ensure that if a user is in multiple groups they only get enumerated once and also any circular group nesting are taken care of as well seems to work well for me so i thought I'd share it.

In the case of this script he $groupName is the DistiguishedName of the Group you want to enumerate the members of.

$repeathashGroup = @{ }
$repeathashUser = @{ }

function Get-member($GroupName){
$Grouppath = "LDAP://" + $GroupName
$groupObj = [ADSI]$Grouppath
foreach($member in $groupObj.Member){
$userPath = "LDAP://" + $member
$UserObj = [ADSI]$userPath
if($UserObj.groupType.Value -eq $null){
if($repeathashUser.ContainsKey($UserObj.distinguishedName.ToString()) -eq $false){
$repeathashUser.add($UserObj.distinguishedName.ToString(),1)
$UserObj.distinguishedName.ToString()

}

}
else{
if($repeathashGroup.ContainsKey($UserObj.distinguishedName.ToString()) -eq $false){
$repeathashGroup.add($UserObj.distinguishedName.ToString(),1)
Get-member($UserObj.distinguishedName)
}
}
}
}

2 comments:

Viama said...

Thanks Glen,

How can I go about adding other attributes from the DL members, other than just their DN? e.g. Email Address and Display Name?

Many thanks

Jon Hewitt

Glen said...

I would suggest you change the line and add the whole object into the hash table eg change

$repeathashUser.add($UserObj.distinguishedName.ToString(),1)

to

$repeathashUser.add($UserObj.distinguishedName.ToString(),$UserObj)

This should then allow you to get any property from the objects stored withing the hashtable. An alternative would be to create your own custom object and store the value in that as well.

cheers
Glen