我想運行一個LDAP查詢,它將返回屬於組織單位OU=Employees
和OU=FormerEmployees
的所有用戶,我沒有得到任何地方。C#LDAP查詢檢索組織單位中的所有用戶
我試過使用distinguishedName
進行搜索,但似乎並不支持通配符。我知道必須有一個更簡單的方法,但我的搜索努力沒有取得任何結果
我想運行一個LDAP查詢,它將返回屬於組織單位OU=Employees
和OU=FormerEmployees
的所有用戶,我沒有得到任何地方。C#LDAP查詢檢索組織單位中的所有用戶
我試過使用distinguishedName
進行搜索,但似乎並不支持通配符。我知道必須有一個更簡單的方法,但我的搜索努力沒有取得任何結果
如果您使用的是.NET 3.5及更新的版本,則可以使用PrincipalSearcher
和「按示例查詢」主體做你的搜索:
// create your domain context and define what container to search in - here OU=Employees
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "OU=Employees,DC=YourCompany,DC=com");
// define a "query-by-example" principal - here, we search for a UserPrincipal
// that is still active
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.Enabled = true;
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
}
如果您還沒有 - 絕對看MSDN文章Managing Directory Security Principals in the .NET Framework 3.5這很好地說明如何使新功能的最佳使用System.DirectoryServices.AccountManagement
如果你喜歡「舊」 .NET 2.0的風格,你需要創建一個基地DirectoryEntry
對應於喲烏爾OU要枚舉對象,然後你需要創建一個DirectorySearcher
,搜索的對象 - 是這樣的:
// create your "base" - the OU "FormerEmployees"
DirectoryEntry formerEmployeeOU = new DirectoryEntry("LDAP://OU=FormerEmployees,DC=YourCompany,DC=com");
// create a searcher to find objects inside this container
DirectorySearcher feSearcher = new DirectorySearcher(formerEmployeeOU);
// define a standard LDAP filter for what you search for - here "users"
feSearcher.Filter = "(objectCategory=user)";
// define the properties you want to have returned by the searcher
feSearcher.PropertiesToLoad.Add("distinguishedName");
feSearcher.PropertiesToLoad.Add("sn");
feSearcher.PropertiesToLoad.Add("givenName");
feSearcher.PropertiesToLoad.Add("mail");
// search and iterate over results
foreach (SearchResult sr in feSearcher.FindAll())
{
// for each property, you need to check where it's present in sr.Properties
if (sr.Properties["description"] != null && sr.Properties["description"].Count > 0)
{
string description = sr.Properties["description"][0].ToString();
}
}
非常感謝。這很有用。我使用了「舊」方法,因爲這是現有代碼的寫法。在使用新方法時是否有性能優勢,如果可以的話,我可以考慮轉換它(我是LDAP例程的新手)。 – BeepBoop
@ user914082:我不認爲「新」S.DS.AM在運行時具有任何性能優勢。它建立在S.DS之上 - 它更容易使用 - 所以你的性能(編寫代碼)會更好 - 但我沒有看到任何運行時性能的好處... –
@marc_s你能幫我在這裏http://stackoverflow.com/questions/40236144/need-all-users-detail-name-email-designation-department-in-the-current-orga – Sak
你的意思**組織單位(OU)** **或**組??這些是完全不同的,行爲不同...... –
我會推薦使用類似[AD Explorer](http://technet.microsoft.com/en-us/sysinternals/bb963907)來測試你的LDAP查詢,並且它們是否工作在這個工具中,把它們放在你的代碼中。 –
@marc_s objectClass是OrganizationalUnit,所以我認爲這是我想要的。 – BeepBoop