问题
c#通过调用cmd输入net user命令添加用户后,命令中设置了/expries:never也就是永不过期,但是在用户管理里面查看该用户的永不过期并没有勾选上。
解决
经过网上摸索,找到了windows的wmic命令可以解决该问题。
当然wmic命令也可以创建用户。网上说wmic命令比net user命令更高级,目前我还不知道。
参考:https://www.windows-commandline.com/wmic-useraccounts/ 命令说明。
Process process = new Process();
process.StartInfo.WorkingDirectory = @"C:/WINDOWS/system32";
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.Verb = "runas";
process.StartInfo.CreateNoWindow = true;
process.Start();
if (add)
{
//添加用户
string cmd = "net user " + username + " " + password + " /ADD /COMMENT:\"" + comment + "\" /FULLNAME:" + username;
log.Info(cmd);
process.StandardInput.WriteLine(cmd);
process.StandardInput.Flush();
//设置账户是否禁用
cmd = "wmic useraccount where name='" + username + "' set disabled=" + userdisabled;
log.Info(cmd);
process.StandardInput.WriteLine(cmd);
process.StandardInput.Flush();
//设置用户是否可以修改账户密码
cmd = "wmic useraccount where name='" + username + "' set passwordchangeable=" + passwordchangeable;
log.Info(cmd);
process.StandardInput.WriteLine(cmd);
process.StandardInput.Flush();
//设置账户密码不过期
cmd = "wmic useraccount where name='" + username + "' set passwordexpires=" + passwordexpires;
log.Info(cmd);
process.StandardInput.WriteLine(cmd);
process.StandardInput.Flush();
//设置为管理员
if (isadmin)
{
log.Info("net LOCALGROUP Administrators " + username + " /add");
process.StandardInput.WriteLine("net LOCALGROUP Administrators " + username + " /add");
}
}
else
{
//删除用户
string cmd = "net user " + username + " /delete";
process.StandardInput.WriteLine(cmd);
process.StandardInput.Flush();
}
//关闭命令输入流,防止卡死
process.StandardInput.Close();
//net localgroup administrators tian /add
StreamReader readerEnd = process.StandardOutput;
StreamReader readerErr = process.StandardError;
process.WaitForExit();
if (process.HasExited)
{
outMsg = readerEnd.ReadToEnd();
errMsg = readerErr.ReadToEnd();
log.Info("outMsg:" + outMsg);
log.Error("errMsg:" + errMsg);
}
process.Close();
感谢网络资源
同时谢谢参考