Process.start()返回不正确的退出代码

问题描述 投票:0回答:2

我正在尝试通过.Net进程重置Windows本地管理员密码,如下所示:

int retVal;
string pEXE = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\cmd.exe";
if (System.IO.File.Exists(pEXE))
{
    Process P = new Process();
    P.StartInfo.FileName = pEXE;
    P.StartInfo.Arguments = "/c " + "net user lAdmin 123";
    P.StartInfo.UseShellExecute = false;
    P.StartInfo.CreateNoWindow = true;
    P.StartInfo.RedirectStandardError = true;
    P.StartInfo.RedirectStandardOutput = true;
    P.StartInfo.RedirectStandardInput = true;
    P.Start();
    P.WaitForExit();
    retVal = P.ExitCode;
}

在两种不同情况下:[1]如果本地管理员帐户用户名是“ lAdmin”,则退出代码将是“ 0”,这表示成功。[2]如果本地管理员帐户用户名是“ Administrator”,则退出代码将是“ 2”,即“系统找不到指定的文件”,但是,如果我在Windows命令提示符下运行此命令,则会得到错误代码“ 2221”是“找不到用户名”。

c# process exit-code
2个回答
1
投票

net.exe仅向用户显示错误代码“ 2221”,以便用户可以在文档中查找此代码,但不会使代码“ 2221”可用于操作系统。

enter image description here

您可以尝试捕获命令的输出,然后解析输出以检索显示给用户的错误代码。但是解析该文本将不是很可靠,因为该文本在操作系统的不同语言中显然会有所不同,并且在将来的Windows更新中也可能会更改。


0
投票
Process test = new Process();
test.StartInfo.FileName = "cmd.exe";
test.StartInfo.Arguments = @"/c fc /b /a C:\temp\debug\1.txt C:\temp\debug\2.txt";
test.StartInfo.RedirectStandardError = true;
test.StartInfo.RedirectStandardOutput = true;
test.StartInfo.UseShellExecute = false;
test.StartInfo.CreateNoWindow = true;
test.Start();


test.WaitForExit();
printLog(test.ExitCode.ToString());
return;

遵循此代码...

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.