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

时间:2014-12-17 22:03:01

标签: c# streamwriter psexec errorlevel console.setout

我正在使用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();

1 个答案:

答案 0 :(得分:0)

我建议使用System.Management.Automation创建PowerShell管道并运行正在运行的脚本。

Executing PowerShell scripts from C#

相关问题