.NET console output and PSExec

2019-08-09 17:27发布

I'm running PSExec Microsoft tool with Process class executing a remote command with its own output like this:

            Process p = new Process();

            string args = @"\\remotemachine -u someuser -p somepass wmic product get name";

            ProcessStartInfo ps = new ProcessStartInfo();
            ps.Arguments = args;
            ps.FileName = psExecFileName;
            ps.UseShellExecute = false;
            ps.CreateNoWindow = true;
            ps.RedirectStandardOutput = true;
            ps.RedirectStandardError = true;

            p.StartInfo = ps;
            p.Start();

            StreamReader output = p.StandardOutput;

            string output = output.ReadToEnd();

where wmic product get name is WMI tool running remotely with its own output listing all installed applications on the remote machine. So, in the output I don't see the output of wmic, at the same time when I'm running PSExec in the command line locally, I can fully see the output of both PSExec and started remotely WMIC. The question is, how can I capture all the output on the local machine? Should I run it in a separate console and try to attach to the console to capture all the output?

More generally, if put plainly, why is the output in the process StandardOutput and in the console when running PSExec directly not the same?

2条回答
\"骚年 ilove
2楼-- · 2019-08-09 17:35

ReadToEnd will wait till the process exit. e.g. a Console.ReadLine() in the psExecFile could block your reading. But you can get the already written stream,

            StreamReader output = p.StandardOutput;
            string line;
            while ((line = output.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
查看更多
Explosion°爆炸
3楼-- · 2019-08-09 17:55

In the console, data written to both StandardOutput and StandardError is displayed in the console.

Within your program you need to look at each individually...try adding something like this at the end:

string error = p.StandardError.ReadToEnd();
查看更多
登录 后发表回答