如何仅从active Directory检索活动用户(未被禁用的用户)
本文关键字:用户 active Directory 检索 活动 何仅 | 更新日期: 2023-09-27 18:11:22
我使用下面的代码来获取Active Directory中所有用户的电子邮件。但是,代码还返回已在Active Directory中禁用的用户。
如何过滤结果以只返回具有活动帐户的用户?
DirectoryEntry entry = new DirectoryEntry("LDAP://MyDomain");
DirectorySearcher dSearch = new DirectorySearcher(entry);
dSearch.Filter = "(objectClass=user)";
foreach (SearchResult sResultSet in dSearch.FindAll())
{
if (sResultSet.Properties["mail"].Count > 0)
Response.Write(sResultSet.Properties["mail"][0].ToString() + "<br/>");
}
我认为活动目录中可能有一个属性来定义帐户是否被禁用,我可以使用这个属性来过滤结果。
我使用的是c# . net。
您可以使用PrincipalSearcher
和"按例查询"主体来进行搜索:
// create your domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// define a "query-by-example" principal - here, we search for enabled UserPrincipal
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.Enabled = true;
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
List<string> emails = new List<string>();
// find all matches
foreach(var found in srch.FindAll())
{
UserPrincipal foundUser = found as UserPrincipal;
emails.Add(foundUser.EmailAddress);
}
}
如果你还没有——绝对要阅读MSDN的文章在。net Framework 3.5中管理目录安全主体,它很好地展示了如何充分利用System.DirectoryServices.AccountManagement
中的新特性。或者查看System.DirectoryServices.AccountManagement命名空间上的MSDN文档。
您可以在UserPrincipal
上指定任何属性,并将其用作PrincipalSearcher
的"按例查询"。