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)
}
}
}
}
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)
}
}
}
}