Search code examples
c#processpsexec

psexec.exe doesn't work when I create a Process from C#


Long story short...

This doesnt work:

Process p = new Process();
p.StartInfo.FileName = @"External\PsExec.exe";
string file = String.Concat(Path.Combine(Environment.CurrentDirectory,"temp"),@"\iisreset",DateTime.Now.ToString("ddMMyyyy-hhmmssss"),".txt");
p.StartInfo.Arguments = String.Format("-s -u {0}\\{1} -p {2} \\\\{3} iisreset > \"{4}\"", Domain,UserName, Password, machineIP, file);
p.StartInfo.CreateNoWindow = true;
p.Start();
p.WaitForExit();

I'm getting a RPC Unavailable message.

But when I access the command line in the program folder, then i run this: (with the correct parameters), exactly like I specified in the filename/arguments...

External\PsExec.exe -s -u [user] -p [password] \\[ip] iisreset > "[path]"

It works! Do I have to specify anything else in the C# Process ? What could be possibly happening?

Thanks in advance!

EDIT: It works if I put cmd as the FileName and /c PsExec.exe before the arguments. The problem is this way it always show the window.


Solution

  • You cannot redirect standard output using the arguments the way you are doing. That's not how things actually work.

    At the command line, your arguments end when the command interpreter sees the >, and it begins the process of redirecting standard output to the filename.

    To accomplish this in C# you need to use the RedirectStandardOutput property of the StartInfo class, then read from the Process.StandardOutput stream and write to a file.

    The MSDN documentation for RedirectStandardOutput has a short example you can use to get started.