I am currently using PrincipalContext and UserPrincipal to return the users primary groupid.
How can I take this id and find the actual group name?
Also I have code that works correctly to assign the user's primary group, but once I assign them to the group I can not delete them from Domain Users which is the default primary group prior to my change. I have cal开发者_如何学编程led Save()
before trying to remove the domain users group.
My requirements state I must add the user to AD then assign their primary group and then remove them as a member of Domain Users.
Got it finally
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;
Without seeing your code, it is hard to know for sure, but it sounds like you're almost there! I had a similar task a few years ago and this blog article was very helpful to me. This Scripting Guy article talks about the steps in a little more detail.
I don't know if you can do this with System.DirectoryServices.AccountManagement stuff. Microsoft made some common AD tasks easier with that namespace, but I'd be surprised if this was one of them.
With regards to removing the "Domain Users" group assignment, that is not possible until the primary group has been changed.
This is untested pseudo-code, but I think something like this will work.
// get the group
DirectoryEntry groupToAdd = new DirectoryEntry("LDAP://" + groupDistinguishedName);
// add the member
groupToAdd.Properties["member"].Add(userDistinguishedName);
// commit and close
groupToAdd.CommitChanges();
groupToAdd.Close();
You said you already know how to assign the primary group, so once you've done that and committed it, you can remove the "Domain Users" membership.
//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();
For reference, here's a nice AD in C# overview. Hope this helps!
Also, if PowerShell is an option, this looks like it will do almost exactly what you want.
精彩评论