tags:

views:

523

answers:

3

I need to be able to launch a process and read the output into a variable. Then based on the return of the command I can choose to show the full output or just a selected subset.

So to be clear, I want to launch a text based process (psexec actually) and read the output from that command (stdout, stderr, etc) into a variable rather than have it directly outputted to the console.

+3  A: 

You left off some details regarding what kind of process, but I think this article from the Powershell Team Blog has whatever you'd like to do, either from piping the executable's output somewhere or utilizing System.Diagnostics.Process.

Now that the second option sounds like what you want to do, you can use the ProcessStartInfo class to feed in true as the RedirectStandardOutput property, and then read from the StandardOutput property of the Process object to do whatever you want with the output. StandardError works identically.

Pseudo Masochist
Not sure how much clearer you want it. I want to capture output from a command launched by powershell... like popen. That page seems only to list ways to start processse.
vfilby
Right, that example covers launching executables. Utilize the ProcessStartInfo class, specifically the RedirectStandardOutput property to capture what you want.
Pseudo Masochist
Aye, just figured that out at the same time. Any hints on reading data from a stream in powershell?
vfilby
Not much, except that I forsee heavy usage of "new-object" and the System.IO namespace in your future. :)
Pseudo Masochist
Well, it actually seems pretty simple just a ReadToend() method on the stream.
vfilby
Wow...sorry. Just read this full comment stream after posting my answer. Seems like you've got it all figured out. :)
Scott Saad
+1  A: 

As far as reading stuff into variables is concerned, you should just be able to do something like

$output = ps

This will only capture stdout, though, not the verbose, warning or error streams. You can get the exit code of the previous command by testing the special variable $?.

I think a little more information would be of use to provide a more complete answer, but hopefully this is some way towards what you're looking for.

alastairs
+1  A: 

The PowerShell Community Extensions includes Start-Process. This actually returns a System.Diagnostics.Process.

> $proc = Start-Process pslist -NoShellExecute

However, while this returns the Process object it does not allow you to redirect the output prior to executing. To do that one can create their own process and execute it by first modifying the ProcessStartInfo members:

> $proc = New-Object System.Diagnostics.Process
> $proc.StartInfo = New-Object System.Diagnostics.ProcessStartInfo("pslist.exe")
> $proc.StartInfo.CreateNoWindow = $true
> $proc.StartInfo.UseShellExecute = $false
> $proc.StartInfo.RedirectStandardOutput = $true
> $proc.Start()
> $proc.StandardOutput.ReadToEnd()
Scott Saad