Get users from an AD group
I have this code to work with users from a group
DirectorySearcher myGroupSearcher = new DirectorySearcher(myDirectoryEntry);
myGroupSearcher.Filter = String.Format("(&(objectClass=group)(|(cn={0})(dn={0})))", strGroupName);
myGroupSearcher.PropertiesToLoad.Add("member");
SearchResult myGroupSearchResult = myGroupSearcher.FindOne();
if (myGroupSearchResult != null)
{
ResultPropertyValueCollection myUsersInGroup = myGroupSearchResult.Properties["member"];
int intMemberCount = myUsersInGroup.Count;
for (int i = 0; i < intMemberCount; i++)
{
//Split the current result
string[] strProperites = myUsersInGroup[i].ToString().Split(',');
//Get the CN
string strUsername = strProperites[0].Substring(3);
DirectorySearcher myUserSearcher = new Directo开发者_运维技巧rySearcher(myDirectoryEntry);
myUserSearcher.Filter = String.Format("(&(objectClass=user)(|(cn={0})(sAMAccountName={0})))", strUsername);
myUserSearcher.PropertiesToLoad.Add("memberOf");
SearchResult myUserSearchResult = myUserSearcher.FindOne();
//Do some work
}
}
This works for most users, but for some, the strUsername gets turncated depending on how the customers AD looks like (if the user have a CN containing ,). So this solution isnt the most optimal to use. Is there a way to get the samaccount name when searching for members in a group? Or is there a better way?
Assuming you're on .NET 3.5 or newer (or can upgrade to it), you should check out the System.DirectoryServices.AccountManagement
(S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");
// if found....
if (group != null)
{
// iterate over members
foreach (Principal p in group.GetMembers())
{
Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
// do whatever you need to do to those members
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD:
string[] strProperites = myUsersInGroup[i].ToString().Split(new string[] { "cn=" }, StringSplitOptions.RemoveEmptyEntries);
It might be an option to use the System.DirectoryServices.AccountManagement
classes instead of the DirectorySearcher. There is a GroupPrincipal
class which has a Members
property that contains the UserPrincipal
objects.
精彩评论