簡體   English   中英

從廣告組獲取用戶

[英]Get users from an AD group

我有這段代碼可以與一組用戶一起使用

DirectorySearcher myGroupSearcher = new DirectorySearcher(myDirectoryEntry);
myGroupSearcher.Filter = String.Format("(&(objectClass=group)(|(cn={0})(dn={0})))", strGroupName);
myGroupSearcher.PropertiesToLoad.Add("member");

SearchResult myGroupSearchResult = myGroupSearcher.FindOne();

if (myGroupSearchResult != null)
{
    ResultPropertyValueCollection myUsersInGroup = myGroupSearchResult.Properties["member"];

    int intMemberCount = myUsersInGroup.Count;

    for (int i = 0; i < intMemberCount; i++)
    {
        //Split the current result
        string[] strProperites = myUsersInGroup[i].ToString().Split(',');

        //Get the CN
        string strUsername = strProperites[0].Substring(3);

        DirectorySearcher myUserSearcher = new DirectorySearcher(myDirectoryEntry);
        myUserSearcher.Filter = String.Format("(&(objectClass=user)(|(cn={0})(sAMAccountName={0})))", strUsername);
        myUserSearcher.PropertiesToLoad.Add("memberOf");

        SearchResult myUserSearchResult = myUserSearcher.FindOne();

        //Do some work
    }
}

這適用於大多數用戶,但對於某些用戶,strUsername取決於客戶AD的外觀而被轉換(如果用戶的CN包含,)。 因此,此解決方案並不是最適合使用的解決方案。 搜索組中的成員時,是否可以獲取samaccount名稱? 或者,還有更好的方法?

假設您使用的是.NET 3.5或更高版本(或可以升級到.NET 3.5),則應簽出System.DirectoryServices.AccountManagement (S.DS.AM)命名空間。 在這里閱讀所有相關內容:

管理.NET Framework 3.5中的目錄安全性主體

基本上,您可以定義域上下文並輕松查找AD中的用戶和/或組:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

// if found....
if (group != null)
{
   // iterate over members
   foreach (Principal p in group.GetMembers())
   {
      Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
      // do whatever you need to do to those members
   }
}

新的S.DS.AM使得與AD中的用戶和組玩起來非常容易:

string[] strProperites = myUsersInGroup[i].ToString().Split(new string[] { "cn=" }, StringSplitOptions.RemoveEmptyEntries);

可以選擇使用System.DirectoryServices.AccountManagement類而不是DirectorySearcher。 有一個GroupPrincipal類,它具有一個包含UserPrincipal對象的Members屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM