我是 C# 新手,我正在尝试禁用或启用本地计算机上的用户,如下面的代码所示。我正在创建一个 exe 并提示用户输入他们想要启用或禁用的用户名。
现在我想将参数传递给命令提示符并禁用或启用用户。例如:>cmd.exe John Disable。
如何使用 c# 将参数传递给命令提示符并使用下面的相同代码来启用或禁用用户?
class EnableDisableUsers
{
static void Main(string[] args)
{
Console.WriteLine("Enter user account to be enabled or disabled");
string user = Console.ReadLine();
Console.WriteLine("Enter E to enable or D to disable the user account");
string enableStr = Console.ReadLine();
bool enable;
if (enableStr.Equals("E") || enableStr.Equals("e"))
{
PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
// find a user
UserPrincipal username = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, user);
if (user != null)
{
try
{
//Enable User
username.Enabled = true;
username.Save();
Console.WriteLine(user + " Enabled");
}
catch (Exception e)
{
Console.WriteLine("Operation failed - Username is not valid", e.Message);
}
}
Console.ReadLine();
}
else if (enableStr.Equals("D") || enableStr.Equals("d"))
{
PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
// find a user
UserPrincipal username = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, user);
if (user != null)
{
try
{
//Disable User
username.Enabled = false;
username.Save();
Console.WriteLine(user + " Disabled");
}
catch (Exception e)
{
Console.WriteLine("Operation failed - Username is not valid", e.Message);
}
}
Console.ReadLine();
}
}
}