代码之家  ›  专栏  ›  技术社区  ›  Jason Towne

如何从active directory获取属于特定部门的所有用户的列表?

  •  1
  • Jason Towne  · 技术社区  · 16 年前

    我要做的是:

    我想使用vb.net和directoryservices从active directory获取属于特定部门(由用户输入)的所有用户和组的列表。

    有什么建议吗?

    2 回复  |  直到 16 年前
        1
  •  3
  •   marc_s MisterSmith    16 年前

    只要你是在.NET2.0上,那可能就是最好的了。你可以做的是将“部门”条件添加到你的搜索筛选中-这样,你就可以让广告来按部门进行筛选:

    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过滤器基本上允许在“anded”括号内有任意数量的条件( (&....) 围绕着你的两个条件-你可以很容易地扩展到三个条件,就像我做的那样)。

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

    查看MSDN文章 Managing Directory Security Principals in the .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上…但是等等-那只是.NET2上的一个服务包,真的:-)

        2
  •  0
  •   Jason Towne    16 年前

    好吧,这是我想到的。这似乎有效,但我当然愿意接受建议或改进的解决方案。

    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
    
    推荐文章