Friday, January 29, 2010

Enumeration of All Groups for a User (traversing nested groups) in Active Directory

I ran into an odd situation where I needed to be able to enumerate all of the groups that a user was a member. I found a lot of programs and scripts that will list the groups for a user, but none that would traverse nested groups.

The script writes the information to a file for better reviewing later. The output adds indentation to help readability.

Here is my solution.

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

$roles = @{};
$indent = -1;
filter EnumRoles {
    $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.memberOf.Count;
        $("`t"*$indent) + $adsiObj.cn + " [$memberOfCount]";
        if (($memberOfCount -gt 0) -and ($indent -lt 900)) {
            $adsiObj.memberOf | EnumRoles;
        }
    }
    $indent -= 1;
}

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

No comments: