簡體   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