Search code examples
c#system.diagnosticspsexecnetstat

C# and psexec process output redirection issues


I'm trying to create a small program to run on a centralized device. This program will run

"psexec \server(s) netstat -na | findstr "LISTENING""

to collect netstat data from remote nodes (should redirect output to string), then parse the data and compare against a known list. I can run the psexec cmd above without any issues from the cmd line, but when I try to run the same command as a process within my C# program, no data is returned to be parsed. I can see that the netstat is being run (cmd window flashes with netstat results), but the process.standardoutput is not catching the stream. If I use ping or pretty much anything other than psexec as an argument, the stream is caught and the results are shown in my text box. I've also tried setting the filename to psexec.exe and specifying the arguments but I get the same results. Last but not least, if I run psexec without any arguments, I get the help kickback info returned in my textbox. This is true if I'm running psexec.exe as the filename OR if I run cmd.exe as filename with "/c psexec" specified as args.

I'm just trying to get psexec output to be caught when executing locally at this point. I'll worry about psexec to remote machines later. Any help would be MUCH appreciated.

Here's the code:

        System.Diagnostics.Process pProcess = new System.Diagnostics.Process();  
        pProcess.StartInfo.FileName = "cmd.exe";  
        pProcess.StartInfo.Arguments = "/c psexec netstat";  
        pProcess.StartInfo.UseShellExecute = false;  
        pProcess.StartInfo.RedirectStandardOutput = true;     
        pProcess.Start();
        string strOutput = pProcess.StandardOutput.ReadToEnd(); 
        pProcess.WaitForExit();

        if (pProcess.HasExited)
        {
            textBox1.Text = strOutput;
        }
        else
        {
            textBox1.Text = "TIMEOUT FAIL";
        }

Solution

  • I would recommend also capturing the standard error output in case anything is being reported there.

    Also, you may have a disconnect between "bitness" of psexec and your application if you are running on a 64-bit OS. If this is the case, change the platform for the project to match that of psexec rather than building as Any CPU.