2010-04-30 41 views
2

我目前使用PrincipalContext和UserPrincipal來返回用戶主要的組ID。在C#中從AD獲取主組名的最簡單方法是什麼?

如何獲取此ID並找到實際的組名?

此外,我有代碼可以正確地分配用戶的主要組,但是一旦我將它們分配給組,我無法將它們從域用戶(它是默認的主要組)之前進行更改。我在嘗試刪除域用戶組之前調用了Save()

我的需求狀態我必須將用戶添加到AD,然後分配他們的主組,然後將其作爲域用戶的成員刪除。

+0

相關的問題:http://stackoverflow.com/questions/1179858/can-you-find-an-active-directory-users-primary-group-in-c – Josh 2010-04-30 15:28:48

回答

2

得到它終於

PrincipalContext principalContext = this.principalFactory.CreateActiveDirectoryManagementContext(locationType); 
     UserPrincipal userPrincipal = this.principalFactory.CreateUserPrincipal(principalContext, userName); 

     string primaryGroupId = userPrincipal.GetPrimaryGroupId(); 

     PrincipalSearchResult<Principal> results = 
      userPrincipal.GetAuthorizationGroups(); 

     foreach (Principal principal in from principal in results 
             let sid = principal.Sid.ToString() 
             let test = sid.Split('-').ToList() 
             let count = test.Count 
             where test[count - 1].Equals(primaryGroupId) 
             select principal) 
     { 
      return principal.Name; 
     } 

     return string.Empty; 
1

沒有看到你的代碼,很難確切知道,但它聽起來像你幾乎在那裏!幾年前我有類似的任務,這blog article對我很有幫助。這篇Scripting Guy文章更詳細地討論了步驟。

我不知道你是否可以用System.DirectoryServices.AccountManagement做這件事。微軟用這個命名空間讓一些常見的AD任務更容易,但如果這是其中之一,我會感到驚訝。

關於刪除「域用戶」組分配,這是不可能的,直到主組已被更改。

這是未經測試的僞代碼,但我認爲這樣的事情會起作用。

// get the group 
DirectoryEntry groupToAdd = new DirectoryEntry("LDAP://" + groupDistinguishedName); 
// add the member 
groupToAdd.Properties["member"].Add(userDistinguishedName); 
// commit and close 
groupToAdd.CommitChanges(); 
groupToAdd.Close(); 

你說你已經知道如何分配的主要組,所以一旦你做到了這一點,並提交它,你可以刪除「域用戶」的成員。

//Get the domain users 
DirectoryEntry domainUsers = new DirectoryEntry("LDAP://" + domainUserDistinguishedName); 
// Remove the user from the domain user group 
domainUsers.Properties["member"].Remove(userDistinguishedName); 
//Commit the changes 
domainUsers.CommitChanges(); 
domainUsers.Close(); 

作爲參考,這裏是一個很好的AD在C#overview。希望這可以幫助!

+0

喬希,也許我不清楚。我沒有問題添加/刪除組中的用戶。我無法確定給定primaryGroupId的組名是什麼。例如,我可以使用DirectoryEtnry.Properties.Contains(「primaryGroupdId」)並返回1141,但當我擁有1141時,似乎找不到組名。 – madhatter84gn 2010-05-03 12:26:09

0

此外,如果PowerShell是一個選項,this看起來像它幾乎可以完成你想要的。

相關問題