使用Process和ProcessStartInfo在C#上运行psExec

时间:2018-10-24 10:27:33

标签: c# process psexec processstartinfo

我试图在远程服务器上执行bat文件,但是我只能获得打印该bat文件的第一个输出。

d:\ test.bat

@echo off
    echo INFO Hello 1!
    echo ERROR Goodbye 2!
    echo INFO Hello 3!

c#代码为:

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "d:\\psexec.exe";
startInfo.Arguments = "-u user -p pass \\\\192.168.0.1 -c d:\\test.bat";

startInfo.CreateNoWindow = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden; 
startInfo.UseShellExecute = false; 
Process process = new Process();
process.StartInfo = startInfo;
process.OutputDataReceived += CaptureOutput; 
process.ErrorDataReceived += CaptureError;

process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
} //end method

static void CaptureOutput(object sender, DataReceivedEventArgs e)
{
    Console.WriteLine("Output " + e.Data);
}

static void CaptureError(object sender, DataReceivedEventArgs e)
{
    Console.WriteLine("ERROR " + e.Data);
}

该代码的执行打印:

ERROR Connecting to 192.168.0.8...
ERROR 
ERROR 
ERROR Starting PSEXESVC service on 192.168.0.8...
ERROR 
ERROR 
ERROR Connecting with PsExec service on 192.168.0.8...
ERROR 
ERROR 
ERROR Copying \\192.168.0.8\Compartido\Chicon\prueba.bat to 192.168.0.8...
ERROR 
ERROR 
ERROR Starting \\192.168.0.8\Compartido\Chicon\prueba.bat on 192.168.0.8...
ERROR 
ERROR 
ERROR 
ERROR prueba.bat exited on 192.168.0.8 with error code 0.
ERROR 
Output INFO Hello 1!
Output 

但是我需要打印代码:

Output INFO Hello 1!
Output ERROR Goodbye 2!
Output INFO Hello 3!

重要提示:如果我在CMD提示符下执行相同的命令,则运行正常。

d:\\psexec.exe -u user -p pass \\\\192.168.0.1 -c d:\\test.bat

非常感谢

0 个答案:

没有答案