I've been trying to get the console output from running psexec as a process in a c# windows forms application. I've found I can redirect the standardoutput(and standard error) to a specified text file fine in a console application, and can redirect the output when the process used is something other than PsExec (ping for instance), but when I try to use psexec from a windows forms application I usually get an empty line in my logs, or at best I've been able to get the first line. I know psexec has had issues with synchronous redirected output, but even asychronous runs into this problem, but only when used within a Windows Forms Application.
My code for the method called that runs the process:
class Tester
{
static readonly StringBuilder outputText = new StringBuilder();
static readonly StringBuilder errorText = new StringBuilder();
public void Installer(string command, string arguments)
{
using (var psexec = Process.Start(new ProcessStartInfo(
command,
arguments)
{
CreateNoWindow = true,
ErrorDialog = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false
}))
{
psexec.OutputDataReceived += (sendingProcess, outLine) =>
outputText.AppendLine(outLine.Data);
psexec.ErrorDataReceived += (sendingProcess, errorLine) =>
errorText.AppendLine(errorLine.Data);
psexec.BeginOutputReadLine();
psexec.BeginErrorReadLine();
psexec.WaitForExit();
string text = outputText.ToString();
File.AppendAllText(@"C:\test\psexec-test.log", text);
}
}
}
The above works (gives me the output from psexec I expect in a designated file) when called within a console application like this:
class Program
{
static void Main(string[] args)
{
Tester test1 = new Tester();
test1.Installer("PsExec.exe", @"-h \\remoteserver ipconfig");
}
}
However, if I call it from an equivalent Windows Forms Application like so:
public partial class Form1 : Form
{
Tester test = new Tester();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string sendAddress = Address.Text;
test.Installer("psexec.exe", @"-h \\remoteserver ipconfig");
} }
I only get:
Windows IP Configuration
Done! Without the rest of the results from ipconfig.
In the larger application I made everything else does work and I know real work is done (it runs an installer on the remote machine, or multiple remote machines), but I don't get the output from psexec. Is there something I'm missing with the Windows Forms Applications, and how to get the redirection to work with psexec?