Well, first of all, when executing PsExec commands from C#, part of the output is in the StandardOutput
and another part is in the StandardError
for some reason, as mentioned in other posts, but that's not big of a deal.
Now, the problem is: Even when combining the two parts together, the "output" isn't exactly the same compared to what gets displayed on the Command Prompt window. Sometimes it's different and sometimes it's incomplete.
Here's my code:
string args = $@"{computerName} -u ""{username}"" -p ""{password}"" {pathOrCommand}";
var pi = new ProcessStartInfo("PsExec.exe", args);
pi.CreateNoWindow = true;
pi.WindowStyle = ProcessWindowStyle.Hidden;
pi.UseShellExecute = false;
pi.RedirectStandardOutput = true;
pi.RedirectStandardError = true;
using (Process p = Process.Start(pi))
{
var resultLines = new List<string>();
var handler = new DataReceivedEventHandler(delegate (object o, DataReceivedEventArgs e)
{
resultLines.Add(e.Data);
});
p.ErrorDataReceived += handler;
p.OutputDataReceived += handler;
p.BeginErrorReadLine();
p.BeginOutputReadLine();
p.WaitForExit();
string result = string.Join("\r\n", resultLines);
}
An example of when it's different:
When passing the wrong username or password, the following message will be displayed on Command Prompt: *
Logon failure: unknown user name or bad password.
..while the output of the above code will be:
The handle is invalid.
An example of when it's incomplete (this is more important):
When executing this command
PsExec \\computer -u username -p password query session
, the result looks something like this: *SESSIONNAME USERNAME ID STATE TYPE DEVICE >services 0 Disc console someUserName 1 Active rdp-tcp 65537 Listen
..but the output when executing from C# is only:
SESSIONNAME USERNAME ID STATE TYPE DEVICE
So, my questions are:
Why is
Process.StandardOutput
/Process.StandardError
different from the actual output?Is there any way around this?
* I'm only presenting the relevant part of the output here.