2015/04/12

PowerShell/Active Directory - Retrieve Groups managed by a User

I recently had an interesting request at work:
Finding a way to list all the groups a specific user was managing.

If you look into the properties of an Active Directory group object, you will find under the tab "ManagedBy" the name of a user or group who is managing the group and possibly its members if the "Manager can update membership list" is checked.

Group object properties / Managed By tab


This is nice for one group.... what if the user manage tons of them ?



Using the Active Directory Module and some LDAP Filtering

Using the PowerShell Cmdlet Get-ADGroup (from the Active Directory Module), I am using a LDAP filter to find groups that contain the user DistinguishedName in the ManagedBy attribute.


# Retrieve the groups managed by the current user
Get-ADGroup -LDAPFilter "(ManagedBy=$((Get-ADuser -Identity $env:username).distinguishedname))"



For better performance and depending on the size of your Active Directory, I would also recommend to use the -SearchBase to better scope the search range of your query... and possibly use the -ResultSize if you expect a long list of groups.

Example:
# Retrieve the groups managed by the current user
# and only search from "OU=Groups,DC=FX,DC=Lab"
Get-ADGroup -LDAPFilter "(ManagedBy=$((Get-ADuser -Identity $env:username).distinguishedname))" -SearchBase "OU=Groups,DC=FX,DC=Lab" -ResultSetSize 50



Using ADSI/LDAP

If you don't want to rely on the Active Directory Module, you can also use ADSI.
Using the same above LDAP filter, we can query Active Directory this way:

# Distinguished Name of the user
$DN = "CN=TestUser,OU=User,DC=FX,DC=Lab"

# Retrieve the groups managed by this user
([ADSISearcher]"(&(objectCategory=group)(ManagedBy=$DN))").findall()



You will then need to select the properties that you want to output.

For example:
([ADSISearcher]"(&(objectCategory=group)(ManagedBy=$DN))").findall().properties |
ForEach-Object -Process {

    # Output the current object with only Name, DN and ManagedBy properties
    [pscustomobject][ordered]@{
        GroupName = $Psitem.name -as [string]
        GroupDistinguishedName = $Psitem.distinguishedname -as [string]
        GroupManagedby = $Psitem.managedby -as [string]
    }
}




Extra: Get all the groups that contains a manager



# Retrieve the groups managed by the current user
Get-ADGroup -LDAPFilter "(ManagedBy=*)" -SearchBase "OU=Groups,DC=FX,DC=Lab" -Properties ManagedBy




Other Resources



  • about_ActiveDirectory_Filter
    • Describes the syntax and behavior of the search filter supported by the Active Directory module for Windows PowerShell.


Thanks for reading! If you have any questions, leave a comment or send me an email at fxcat@lazywinadmin.com. I invite you to follow me on Twitter @lazywinadm / Google+ / LinkedIn. You can also follow the LazyWinAdmin Blog on Facebook Page and Google+ Page.