Sunday, January 31, 2010

Enumeration of All Users in a Group (traversing nested groups) in Active Directory

As a counter part to my previous post, I created a dual of the script which enumerates Groups and their members.

#
#    Enumerate All Users for a Group (including traversing nested groups) 
#        @param distinguishedName - The distinguished name of the object you want to traverse
#    Brock Moeller
#    12/16/2009
#
param (
    $distinguishedName = "CN=SuperGroup,OU=Groups,DC=serv,DC=ubercorp,DC=com" 
)

$roles = @{};
$indent = -1;
filter EnumMember {
    $indent += 1;
    if ($_ -is [System.DirectoryServices.DirectoryEntry]){
        $adsiObj = $_;
    } else {
        $adsiObj = New-Object System.DirectoryServices.DirectoryEntry("LDAP://" + $_);
    }
    if ((-not [String]::IsNullOrEmpty($adsiObj.cn)) -and (-not $roles.ContainsKey($adsiObj.cn))){
        $roles[$adsiObj.cn] = 1;
        $memberOfCount = $adsiObj.member.Count;
        $("`t"*$indent) + $adsiObj.cn + " [$memberOfCount]";
        if (($memberOfCount -gt 0) -and ($indent -lt 900)) {
            $adsiObj.member | EnumRoles;
        }
    }
    $indent -= 1;
}

$user = [adsi]"LDAP://$distinguishedName";
$user;
$buffer = $user.Path + "`n";
$user | EnumMember | % { $buffer += $_ + "`n" };
"Buffer: " + $buffer.ToString();
[System.IO.File]::WriteAllText("$pwd\$($user.cn).txt", $buffer.ToString());

No comments: