2011-06-20 58 views
0

我在.net 2.0中工作,需要檢索給定AD組的所有用戶。我有以下方法可以返回組中的所有成員,但它不返回將傳遞組作爲其主組的用戶。我還需要做些什麼才能讓這些用戶也參與其中?如何檢索組中的用戶,包括主要組用戶

/// <summary> 
/// Gets the group child users. 
/// </summary> 
/// <param name="parentGroup">The parent group.</param> 
/// <returns></returns> 
public List<ADUser> GetGroupChildUsers(ADGroup parentGroup) 
{ 
    List<ADUser> list = new List<ADUser>(); 

    DirectoryEntry entry = GetDirectoryEntry(LdapBaseString); 

    DirectorySearcher searcher = new DirectorySearcher(entry); 
    searcher.Filter = string.Format("(&(objectCategory=person)(memberOf={0}))", parentGroup.DN); 

    searcher.PropertiesToLoad.Add("objectGUID"); 
    searcher.SizeLimit = MaxReturnCount; 

    SearchResultCollection results = searcher.FindAll(); 

    foreach (SearchResult result in results) { 
     Guid guid = new Guid((byte[])result.Properties["objectGUID"][0]); 
     list.Add(GetUserByGuid(guid)); 
    } 

    if (list.Count <= 0) { 
     return null; 
    } else { 
     return list; 
    } 
} 
+0

前段時間我有一個類似的問題,這可能有幫助。我只需要提取機器或只提取用戶名,而不是一切。 http://stackoverflow.com/questions/6252785/winnt-giving-to-much-information-i-need-to-narrow-down-to-just-machine-names – sealz

回答

3

用戶的主要基團由一個用戶的屬性primaryGroupID給出。實際上,primaryGroupID包含字符串格式的主組的RID。這就是爲什麼我首先得到您要找的用戶組的SID,然後我計算(糟糕的)RID,然後搜索包含RID的用戶primaryGroupID

/* Connection to Active Directory 
*/ 
DirectoryEntry deBase = new DirectoryEntry("LDAP://WM2008R2ENT:389/dc=dom,dc=fr"); 

/* Directory Search for agroup 
*/ 
string givenGrpName = "MonGrpSec"; 
DirectorySearcher dsLookFor = new DirectorySearcher(deBase); 
dsLookFor.Filter = string.Format ("(sAMAccountName={0})", givenGrpName); 
dsLookFor.SearchScope = SearchScope.Subtree; 
dsLookFor.PropertiesToLoad.Add("cn"); 
dsLookFor.PropertiesToLoad.Add("objectSid"); 

SearchResult srcGrp = dsLookFor.FindOne(); 

/* Get the SID 
*/ 
SecurityIdentifier secId = new SecurityIdentifier(srcGrp.Properties["objectSid"][0] as byte[], 0); 

/* Find The RID (sure exists a best method) 
*/ 
Regex regRID = new Regex(@"^S.*-(\d+)$"); 
Match matchRID = regRID.Match(secId.Value); 
string sRID = matchRID.Groups[1].Value; 

/* Directory Search for users that has a particular primary group 
*/ 
DirectorySearcher dsLookForUsers = new DirectorySearcher(deBase); 
dsLookForUsers.Filter = string.Format("(primaryGroupID={0})", sRID); 
dsLookForUsers.SearchScope = SearchScope.Subtree; 
dsLookForUsers.PropertiesToLoad.Add("cn"); 

SearchResultCollection srcUsers = dsLookForUsers.FindAll(); 

foreach (SearchResult user in srcUsers) 
{ 
    Console.WriteLine("{0} is the primary group of {1}", givenGrpName, user.Properties["cn"][0]); 
}