using System;
using System.DirectoryServices.AccountManagement;
class Program
{
static void Main(string[] args)
{
// 定义新用户的用户名和密码
string username = "NewUser";
string password = "P@ssw0rd";
// 创建用户
CreateUser(username, password);
// 将用户加入管理员组
AddUserToAdminGroup(username);
Console.WriteLine("用户创建并成功加入管理员组。");
}
static void CreateUser(string username, string password)
{
using (PrincipalContext context = new PrincipalContext(ContextType.Machine))
{
// 检查用户是否已存在
if (UserPrincipal.FindByIdentity(context, username) == null)
{
// 创建新用户
UserPrincipal user = new UserPrincipal(context)
{
Name = username,
Description = "新创建的用户",
UserCannotChangePassword = true,
PasswordNeverExpires = true
};
// 设置密码
user.SetPassword(password);
// 保存用户
user.Save();
}
else
{
Console.WriteLine("用户已存在。");
}
}
}
static void AddUserToAdminGroup(string username)
{
using (PrincipalContext context = new PrincipalContext(ContextType.Machine))
{
// 获取管理员组
GroupPrincipal adminGroup = GroupPrincipal.FindByIdentity(context, "Administrators");
if (adminGroup != null)
{
// 获取用户
UserPrincipal user = UserPrincipal.FindByIdentity(context, username);
if (user != null)
{
// 检查用户是否已经在管理员组中
if (!adminGroup.Members.Contains(user))
{
// 将用户加入管理员组
adminGroup.Members.Add(user);
adminGroup.Save();
}
else
{
Console.WriteLine("用户已经在管理员组中。");
}
}
else
{
Console.WriteLine("用户不存在。");
}
}
else
{
Console.WriteLine("管理员组不存在。");
}
}
}
}