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

时间:2010-03-18 18:34:06

标签: vb.net .net-2.0 active-directory directoryservices

这是我正在尝试做的事情:

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

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

只要您使用的是.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过滤器基本上允许你在“anded”括号内有任意数量的条件(围绕你的两个条件(&....) - 你可以像我一样轻松地将它扩展到三个条件。)

如果您有机会升级到.NET 3.5,可以使用名为System.DirectoryServices.AccountManagement的新命名空间,它可以提供更好,更直观的方法来处理用户,组,计算机和搜索。< / p>

查看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上......但等等 - 这只是.NET 2上的服务包,真的: - )

答案 1 :(得分: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))"
  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