Search code examples
c#psexec

Running exe with parameters doesn't work


var p = Process.Start(@"c:\PsTools\PsExec.exe", @"C:\Windows\System32\notepad.exe");
var err = p.StandardError.ReadToEnd();
var msg = p.StandardOutput.ReadToEnd();
lblStatusResponse.Text = "Err: " + err + "Msg: " + msg;

Why is my code not working?

I getting error:

System.InvalidOperationException: StandardError has not been redirected.

But when I add following:

p.StartInfo.RedirectStandardError = true;
var p = Process.Start(@"c:\PsTools\PsExec.exe", @"C:\Windows\System32\notepad.exe");) 

it still gets the same error.

The main problem is that I wanna execute a exe with arguments, but I can't get it to work.


Solution

  • The following code generates a new p, this ignoring the settings you change in the previous instance:

    var p = Process.Start(@"c:\PsTools\PsExec.exe", @"C:\Windows\System32\notepad.exe");) 
    

    So it doesn't really matter whether you initialize p like this

    p.StartInfo.RedirectStandardError = true;
    

    or not.

    What you need to do

    You need to create a ProcessStartInfo object, configure it and then pass it to Process.Start.

    ProcessStartInfo p = new ProcessStartInfo(@"c:\PsTools\PsExec.exe", @"C:\Windows\System32\notepad.exe");
    p.UseShellExecute = false;
    p.RedirectStandardError = true;
    p.RedirectStandardOutput = true;
    
    Process proc = Process.Start(p);
    
    var err = proc.StandardError.ReadToEnd();
    var msg = proc.StandardOutput.ReadToEnd();