2015-11-05 68 views
0

我有這個小問題。活動目錄 - 獲取所有用戶屬於經理

我想獲得所有擁有相同管理器的用戶。

目前,我有代碼可以做到這一點,但問題是它得到所有的用戶。然後,我循環遍歷所有用戶,並匹配經理。 這樣做的問題在於,如果有100 000個用戶,這會花費太多時間。

我當前的代碼:

 UserPrincipal managerP = UserPrincipal.FindByIdentity(GetPrincipalContext(), IdentityType.SamAccountName, sAMManager); 

     if (managerP != null) 
     { 
      using (UserPrincipal user = new UserPrincipal(GetPrincipalContext())) 
      { 
       using (PrincipalSearcher search = new PrincipalSearcher(user)) 
       { 
        search.QueryFilter = user; 

        foreach (UserPrincipal userP in search.FindAll()) 
        { 
         if (managerP.SamAccountName.ToLower() == sAMManager.ToLower()) 
         { 
          //Add 'userP' to list. 
         } 
        } 
       } 
      } 
     } 

如何我可以改變這一點,這樣我可以得到所有的用戶屬於管理者,而不是讓他們都第一?

回答

1

你可以用一個簡單的LDAP查詢做到這一點:

 using (DirectorySearcher searcher = new DirectorySearcher(new DirectoryEntry("LDAP://contoso.com"))) 
     { 
      searcher.Filter = "(&(objectCategory=person)(objectClass=user)(manager=CN=John Doe,CN=Users,DC=contoso,DC=com))"; 

      searcher.PropertiesToLoad.AddRange(new string[] { "givenName", "sn", "sAMAccountName" }); 

      foreach (SearchResult item in searcher.FindAll()) 
      { 
       Console.WriteLine(String.Format("User {0} {1} ({2}) works for John Doe", item.Properties["givenName"].ToString(), item.Properties["sn"].ToString(), item.Properties["sAMAccountName"].ToString())); 
      } 
     } 
+0

謝謝:),問題解決了:) –

相關問題