繁体   English   中英

如何从Active Directory中获取属于特定部门的所有用户的列表?

[英]How can I get a list of all users that belong to a specific department from Active Directory?

这是我想做的事情:

我想使用VB.Net和DirectoryServices从Active Directory中获取属于特定部门(由用户输入)的所有用户和组的列表。

有什么建议么?

只要您使用的是.NET 2.0,那可能就和它一样好。 您可以做的是在搜索过滤器中添加“部门”条件-这样,您就可以将其留给AD来按部门进行过滤:

Private Sub GetUsersByDepartment(ByVal department as String)
  Dim deGlobal As DirectoryEntry = New DirectoryEntry(ADPath, ADUser, ADPassword)
  Dim ds As DirectorySearcher = New DirectorySearcher(deGlobal)

  ds.Filter = "(&(objectCategory=person)(objectClass=user)(department=" & department & "))"
  ds.SearchScope = SearchScope.Subtree

  For Each sr As SearchResult In ds.FindAll
    Dim newDE As DirectoryEntry = New DirectoryEntry(sr.Path)
    If Not newDE Is Nothing Then
          *Do Something*
    End If
  Next
End Sub

这肯定会有所帮助-我希望作为C#程序员,我没有搞砸您的VB代码!

LDAP过滤器基本上允许您在“与”括号内包含任意数量的条件(&....)围绕两个条件的(&....) -您可以像我一样轻松地将其扩展为三个条件)。

如果您有机会升级到.NET 3.5,则可以使用一个名为System.DirectoryServices.AccountManagement的新名称空间,该名称空间提供了更好,更直观的方法来处理用户,组,计算机和搜索。

请查阅MSDN文章.NET Framework 3.5中的管理目录安全性主体”,以了解有关此内容的更多信息。

您可以做的是例如“按示例搜索”,因此您可以创建一个UserPrincipal并设置要过滤的那些属性,然后将该对象作为“模板”进行搜索:

UserPrincipal user = new UserPrincipal(adPrincipalContext);
user.Department = "Sales";

PrincipalSearcher pS = new PrincipalSearcher(user);

PrincipalSearchResult<Principal> results = pS.FindAll();

// now you could iterate over the search results and do whatever you need to do

确实很整洁! 但是,不幸的是,仅在.NET 3.5上....但是,等等-那只是.NET 2之上的Service Pack,真的是:-)

好吧,这就是我的想法。 它似乎可行,但我当然愿意提出建议或改进解决方案。

Private Sub GetUsersByDepartment(ByVal department as String)
  Dim deGlobal As DirectoryEntry = New DirectoryEntry(ADPath, ADUser, ADPassword)
  Dim ds As DirectorySearcher = New DirectorySearcher(deGlobal)

  ds.Filter = "(&(objectCategory=person)(objectClass=user))"
  ds.SearchScope = SearchScope.Subtree

  For Each sr As SearchResult In ds.FindAll
    Dim newDE As DirectoryEntry = New DirectoryEntry(sr.Path)
    If Not newDE Is Nothing Then
      If newDE.Properties.Contains("department") Then
        If newDE.Properties("department")(0).ToString = department Then
          *Do Something*
        End If
      End If
    End If
  Next

End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM