[英]Get users from an AD 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 DirectorySearcher(myDirectoryEntry);
myUserSearcher.Filter = String.Format("(&(objectClass=user)(|(cn={0})(sAMAccountName={0})))", strUsername);
myUserSearcher.PropertiesToLoad.Add("memberOf");
SearchResult myUserSearchResult = myUserSearcher.FindOne();
//Do some work
}
}
这适用于大多数用户,但对于某些用户,strUsername取决于客户AD的外观而被转换(如果用户的CN包含,)。 因此,此解决方案并不是最适合使用的解决方案。 搜索组中的成员时,是否可以获取samaccount名称? 或者,还有更好的方法?
假设您使用的是.NET 3.5或更高版本(或可以升级到.NET 3.5),则应签出System.DirectoryServices.AccountManagement
(S.DS.AM)命名空间。 在这里阅读所有相关内容:
基本上,您可以定义域上下文并轻松查找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
}
}
新的S.DS.AM使得与AD中的用户和组玩起来非常容易:
string[] strProperites = myUsersInGroup[i].ToString().Split(new string[] { "cn=" }, StringSplitOptions.RemoveEmptyEntries);
可以选择使用System.DirectoryServices.AccountManagement
类而不是DirectorySearcher。 有一个GroupPrincipal
类,它具有一个包含UserPrincipal
对象的Members
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.