如何在C#中运行Psexec.exe时捕获%ERRORLEVEL%,保存到日志文件

本文关键字:%ERRORLEVEL% 保存 文件 日志 运行 exe Psexec | 更新日期: 2023-09-27 18:34:28

我正在使用psexec.exe在大量计算机上安装一些软件。 我希望能够捕获 %ERRORLEVEL%(或其 c# 等效项(并将它们写入 TXT 文件。 ( cmd.exe 在 6440-nbpb00f51w 上退出,错误代码为 0。

经过广泛的研究,我发现了几种可能性。 我的最终目标是拥有一个.CSV 文件。 每一行将具有计算机名称和 psexec 命令的输出。 使用此数据,我将能够确定更新在哪些计算机上成功。

string[] pcnamearray = new string[] {"COMPUTERNAME1", "COMPUTERNAME2"};
foreach (string i in pcnamearray)
{
    Process p = new Process();
    string psexeclaunch = "psexec.exe";
    p.StartInfo.FileName = psexeclaunch;
    p.StartInfo.RedirectStandardOutput = false;
    p.StartInfo.UseShellExecute = true;
    p.StartInfo.CreateNoWindow = false;
    string arg = "/silent";
    p.StartInfo.Arguments = @" -i ''" + i + @" -u mydomain'admin -p mypassword -h                -e cmd.exe /c start ''networkserver'sw'myfile.exe" + arg;
    p.Start();
}

不是在这里找人为我写代码的人。 我在这里向人们征求他们的建议,或者过去在这方面的经验。 我知道有几种不同的方法可用。 理想情况下,我更喜欢为每个结果留一行简短的甜蜜线,但是如果我必须获取整个输出并使用宏将它们缩减为更具可读性的形式,那也没关系。

到目前为止,我已经尝试过:

Console.WriteLine(p.StandardOutput.ReadToEnd());

和。。。

System.IO.File.WriteAllLines(@"C:'Users'areu2447'Desktop'UpdateDAT'Final'out.txt", lines);

和。。。

FileStream filestream = new FileStream(@"C:'Users'areu2447'Desktop'UpdateDAT'Final'out.txt", FileMode.Append);
var streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);

在我看来,最后一个是最好的,但似乎无法让它工作。 我尝试将其包含在我的 foreach 循环中,但文件正被另一个进程使用,因此在查看它之后,我发现它需要独立存在。 即使仅凭它,我仍然无法让它工作。

请帮助/建议!

通过使用以下内容,我能够让它实际修改我的 TXT 文件,即使没有添加任何内容:

                    System.IO.StreamReader reader = p.StandardOutput;
                    String sRes = reader.ReadToEnd();
                    StreamWriter SW;
                    SW = File.CreateText(@"C:'Users'areu2447'Desktop'UpdateDAT'Final'out.txt");
                    SW.WriteLine(sRes);
                    SW.Close();
                    Console.WriteLine("File Created Successfully");
                    reader.Close();

如何在C#中运行Psexec.exe时捕获%ERRORLEVEL%,保存到日志文件

我建议使用System.Management.Automation来创建PowerShell管道并在进程中运行脚本。

从 C# 执行 PowerShell 脚本