我搜索过高低,阅读了无数页面和有关类似主题的问题,但尚未找到一个问题,要求完全符合这一点或适用于我的情况:
我有一个使用System.Diagnostics.Process的C#程序,并利用RedirectStandardOutput和BeginOutputReadLine方法以及OutputDataReceived事件将我的进程的输出重新路由到文本框中。正在执行的命令如下:
./PsExec.exe \\MACHINENAME -u USERNAME -p PASSWORD cmd /c \\RemotePath\BatchFile.bat arg1 arg2 arg3
当我在本地计算机上的cmd窗口中运行它时,它会输出我的批处理文件中的所有文本和信息,但无论出于何种原因,当我通过C#代码中的Process重定向它时,唯一的问题是输出到我的文本框是:
PsExec v2.11 - Execute processes remotely
Copyright (C) 2001-2014 Mark Russinovich
Sysinternals - www.sysinternals.com
Connecting to MACHINENAME...
Starting PSEXESVC service on MACHINENAME...
Connecting with PsExec service on MACHINENAME...
Starting cmd on MACHINENAME...
cmd exited on MACHINENAME with error code 0.
我的问题是,有没有办法让远程cmd的整个输出重定向到我的程序? (即如果我用“ipconfig”替换“\ RemotePath \ BatchFile.bat”以便ipconfig在远程计算机上运行,我可以将ipconfig信息重定向到我程序中的文本框中。)
编辑:此处添加了代码
string cmd = @"./PsExec.exe \\MACHINENAME -u USERNAME -p PASSWORD cmd /c \\RemotePath\" + batchToExecute + " " + args;
var process = new Process();
process.StartInfo.CreateNoWindow = false; //False for testing
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.FileName = "C:\\Windows\\System32\\cmd.exe";
process.StartInfo.Arguments = ("/c " + cmd);
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
{
if (batchToExecute.Equals(batchName1)) { output1 += (e.Data + "\n"); }
else if (batchToExecute.Equals(batchName2)) { output2 += (e.Data + "\n"); }
else if (batchToExecute.Equals(batchName3)) { output3 += (e.Data + "\n"); }
};
process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
{
if (batchToExecute.Equals(batchName1)) { output1 += (e.Data + "\n"); }
else if (batchToExecute.Equals(batchName2)) { output2 += (e.Data + "\n"); }
else if (batchToExecute.Equals(batchName2)) { output3 += (e.Data + "\n"); }
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
Console.WriteLine("ExitCode: {0}", process.ExitCode);
int processReturn = process.ExitCode;
process.Close();