PenguinKenny
PenguinKenny

Reputation: 80

How to retrieve each parent group of an Active Directory group

I have an Active Directory set up with a number of groups, levels of sub-groups, and then users within those sub groups.

I want to specify a group name and retrieve all groups that the group belongs to (either immediately or further up the hierarchy, not important which).

I have code which finds groups that a user belongs to and iterates through them to see if they match with a specified group name, but I can't figure out how to specify a group and search for those groups.

IADsUser *user_object = NULL;
IADsMembers *members;

// ...
// Get object via ADsGetObject
// ...

// Provides me with a list of groups that the user belongs to
user_object->Groups(&members); 

The IADsGroup class does not contain a Groups() function so I cannot see how I can retrieve a list of groups that a group belongs to.

Upvotes: 2

Views: 956

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40858

You can read the memberOf attribute of the group, using IADs::GetEx.

If you have an IADsGroup group_object:

HRESULT hr;
VARIANT groups;
VariantInit(&groups);
hr = group_object->GetEx(CComBSTR("memberOf"), &groups);

The groups variable will now be a VARIANT array containing the distinguishedName of all the groups. If you want to get the friendly name of each one, then you'll need to bind to each group (using ADsGetObject) to get an IADsGroup object for that group.

The memberOf attribute does have some caveats that you should be aware of, which I wrote about here, but if you're on a single-domain environment with no external, trusted domains, then it shouldn't matter to you.

Note that the return value hr might be E_ADS_PROPERTY_NOT_FOUND if it is not a member of any other groups. Active Directory in general treats empty attributes as non-existent.

Upvotes: 2

Related Questions