Archive for March, 2007

Using PowerShell to find nested Groups for Active Directory Migration

I’ve been involved in an Active Directory Migration lately and one of the things that was taking a lot of time was finding the groups for a group of users and then finding the nested groups. Why, you might ask? Well in this particular instance it was easier for us to migrate groups first than users but we had to make sure we got all the groups for the users we wanted to migrate moved over first.

The first part of the script involves search Active Directory for the user we wish to find group membership for. This is pretty easy:
#Setup Tasks
$query = new-object system.directoryservices.directorysearcher
$root = [adsi]“”

#Setup for Query
$query.searchroot=[adsi]$(“LDAP://”+$root.distinguishedName)
$query.Filter = “(&(objectCategory=user)(objectClass=person)(samAccountName=$accountName))”
$query.SearchScope=“Subtree”

The next thing to do after we find the user is to get the memberOf Property:
$ADobject.psbase.Properties[“memberOf”]

So I found it was easy enough to get a list of groups for a user but how could a get a list for several users without getting duplicates? The logical thing seemed like a hashtable:
$groups = @{}
foreach ( $user in $users ) {
foreach ($group in Get-Groups $user)
{
$groupName=$($group.split(“,”)[0]).split(“=”)[1] if(!$groups.Contains($groupname)){$groups.Add($groupname,$group)}
}
}

The Properties[“memberOf”] returns a collection of distinguished names, (CN=GroupName,OU=Groups,DC=domain,DC=local), so the above code splits up that string to extract the groupName to be the key for the hashtable and then the DN as the value. After this it is simply a case of connecting to each group and listing the memberOf property to see if there is any nested groups.

The code will only check 1 level deep so if you have a chain of nested groups you’ll have to check it manually.

To Run the script just run .\GetGroups “username1″,”username2″,”username3″. Please let me know what you think.

FindNestedGroups.ps1.txt (.91 KB)

Read more