我目前使用PrincipalContext和UserPrincipal来返回用户主要的组ID。在C#中从AD获取主组名的最简单方法是什么?
如何获取此ID并找到实际的组名?
此外,我有代码可以正确地分配用户的主要组,但是一旦我将它们分配给组,我无法将它们从域用户(它是默认的主要组)之前进行更改。我在尝试删除域用户组之前调用了Save()
。
我的需求状态我必须将用户添加到AD,然后分配他们的主组,然后将其作为域用户的成员删除。
我目前使用PrincipalContext和UserPrincipal来返回用户主要的组ID。在C#中从AD获取主组名的最简单方法是什么?
如何获取此ID并找到实际的组名?
此外,我有代码可以正确地分配用户的主要组,但是一旦我将它们分配给组,我无法将它们从域用户(它是默认的主要组)之前进行更改。我在尝试删除域用户组之前调用了Save()
。
我的需求状态我必须将用户添加到AD,然后分配他们的主组,然后将其作为域用户的成员删除。
得到它终于
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;
没有看到你的代码,很难确切知道,但它听起来像你几乎在那里!几年前我有类似的任务,这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。希望这可以帮助!
乔希,也许我不清楚。我没有问题添加/删除组中的用户。我无法确定给定primaryGroupId的组名是什么。例如,我可以使用DirectoryEtnry.Properties.Contains(“primaryGroupdId”)并返回1141,但当我拥有1141时,似乎找不到组名。 – madhatter84gn 2010-05-03 12:26:09
此外,如果PowerShell是一个选项,this看起来像它几乎可以完成你想要的。
相关的问题:http://stackoverflow.com/questions/1179858/can-you-find-an-active-directory-users-primary-group-in-c – Josh 2010-04-30 15:28:48