在Active Directory组内通过查询查找用户
本文关键字:查询 查找 用户 Active Directory | 更新日期: 2023-09-27 18:26:58
给定一个有很多成员的特定组,我想在该组中进行查询,以查找DisplayName匹配的成员。
下面的代码是我想要实现的非功能性示例。请注意,我不想先加载整个列表,然后应用"where",我已经可以这样做了,而且速度很慢,因为组很大。
public static List<Principal> FindUsersOfGroup(string groupName, string displayNameQuery)
{
using (var context = new PrincipalContext(ContextType.Machine, Environment.MachineName))
{
var search = new GroupPrincipal(context);
search.SamAccountName = groupName;
// This where doesn't work, but is what I'm looking for.
search.Members.Where(m => m.DisplayName == displayNameQuery + "*");
using (var ps = new PrincipalSearcher(search))
{
// Want to get all members that match the query AND belong to the group.
return ps.FindAll().ToList();
}
}
}
另外,在我的真实代码中,上下文是Domain,我故意替换了它。
您可以使用DirectorySearcher类执行类似操作:
using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + Environment.UserDomainName))
{
using (DirectorySearcher searcher = new DirectorySearcher(
entry,
string.Format(
"(&(objectCategory=person)(objectClass=user)(displayName={0}*)(memberof={1}))",
displayNameQuery,
groupName)))
{
searcher.PropertiesToLoad.Add("samAccountname"); //You can specify which properties you want to load. If you don't specify properties, by default you will get a lot of properties. Loading specific properties is better in terms of performance
using (var results = searcher.FindAll())
{
foreach (var result in results.Cast<SearchResult>())
{
//Do something with result
var properties = result.Properties;
//Example
var samAccountName = properties["samAccountName"][0];
//...
}
}
}
}
在这种情况下,groupName
是组的可分辨名称(例如,CN=Administrators,CN=Builtin,DC=dnb,DC=lab)