我在Active Directory中为不同的用户组设置了不同的OU,我想要使用C#获取特定OU的所有用户。在特定OU Active Directory中搜索用户
目前我有这个过滤器,但它返回的所有用户的所有OU
(&(objectClass=User)(objectCategory=Person))
请帮我在使用LDAP
感谢
我在Active Directory中为不同的用户组设置了不同的OU,我想要使用C#获取特定OU的所有用户。在特定OU Active Directory中搜索用户
目前我有这个过滤器,但它返回的所有用户的所有OU
(&(objectClass=User)(objectCategory=Person))
请帮我在使用LDAP
感谢
您可以使用PrincipalSearcher
找出特定用户的用户和一个“按实例查询”的委托人来做您的搜索:
// LDAP string to define your OU
string ou = "OU=Sales,DC=YourCompany,DC=com";
// set up a "PrincipalContext" for that OU
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "Yourcompany.com", ou))
{
// define the "query-by-example" user (or group, or computer) for your search
UserPrincipal qbeUser = new UserPrincipal(ctx);
// set whatever attributes you want to limit your search for, e.g. Name, etc.
qbeUser.Surname = "Smith";
// define a searcher for that context and that query-by-example
using (PrincipalSearcher searcher = new PrincipalSearcher(qbeUser))
{
foreach (Principal p in searcher.FindAll())
{
// Convert the "generic" Principal to a UserPrincipal
UserPrincipal user = p as UserPrincipal;
if (user != null)
{
// do something with your found user....
}
}
}
如果你还没有 - 绝对阅读MSDN文章Managing Directory Security Principals in the .NET Framework 3.5,它很好地展示了如何充分利用System.DirectoryServices.AccountManagement
中的新功能。或者查看MSDN documentation on the System.DirectoryServices.AccountManagement命名空间。
当然,这取决于你的需要,你可能想在你创建一个“查询通过例如”用户主体指定其他属性:
DisplayName
(通常为:第一名称+空格+姓氏)SAM Account Name
- 你的Windows/AD帐户名User Principal Name
- 你的 “[email protected]” 样式名可以SPE将UserPrincipal
上的任何属性都作为属性,并将它们用作您的PrincipalSearcher
的“查询范例”。
一种选择是当你创建DirectoryEntry
对象刚才设置的组织单位(OU):
using (var entry = new DirectoryEntry($"LDAP://OU={unit},OU=Accounts,DC={domain},DC=local"))
{
// Setup your search within the directory
var search = new DirectorySearcher(entry)
{
Filter = "(&(objectCategory=person)(objectClass=user)(memberOf=*))"
};
// Set the properties to be returned
search.PropertiesToLoad.Add("SamAccountName");
// Get the results
var results = search.FindAll();
// TODO Process the results as needed...
}
谢谢您的答复。 但我必须使用ldap来做到这一点 –
@MuhammadTaqi:我的回复***是使用LDAP的***! –