简体   繁体   中英

How to create AD User belonging to Domain Admins group in C#

I'm working on a C# project which auto-creates new Active Directory users and let them access to the AD server.

I have made a general user with the following code, but since the user does not belong to Domain Admins, it could not access to the server.

Domain domain = Domain.GetCurrentDomain();
PrincipalContext context = new PrincipalContext(ContextType.Domain);

UserPrincipal principal = new UserPrincipal(context);
principal.Name = name;
principal.UserPrincipalName = name + "@" + domain.Name;
principal.SamAccountName = name;
principal.Enabled = true;
principal.SetPassword(password);
principal.PasswordNeverExpires = true;
principal.Save();

Is there a way to include which group the new user belong in the code? Or after creating the account, adding the user to Domain Admins group might be another solution but I couldn't figure out how to do this either. Any advice would be appreciated.

You just need to find the group and add the user you created. Like this:

var group = GroupPrincipal.FindByIdentity(context, "Domain Admins");
group.Members.Add(principal);
group.Save();

The code will have to run with credentials that can add someone to the Domain Admins group, which is likely a domain admin account itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM