I want to capture stdout and stderr from a process that I start in a Powershell script and display it asynchronously to the console. I've found some documentation on doing this through MSDN and other blogs.
After creating and running the example below, I can't seem to get any output to be displayed asynchronously. All of the output is only displayed when the process terminates.
$ps = new-object System.Diagnostics.Process
$ps.StartInfo.Filename = "cmd.exe"
$ps.StartInfo.UseShellExecute = $false
$ps.StartInfo.RedirectStandardOutput = $true
$ps.StartInfo.Arguments = "/c echo `"hi`" `& timeout 5"
$action = { Write-Host $EventArgs.Data }
Register-ObjectEvent -InputObject $ps -EventName OutputDataReceived -Action $action | Out-Null
$ps.start() | Out-Null
$ps.BeginOutputReadLine()
$ps.WaitForExit()
In this example, I was expecting to see the output of "hi" on the commandline before the end of program execution because the OutputDataReceived event should have been triggered.
I've tried this using other executables - java.exe, git.exe, etc. All of them have the same effect, so I'm left to think that there is something simple that I'm not understanding or have missed. What else needs to be done to read stdout asynchronously?
Unfortunately asynchronous reading is not that easy if you want to do it properly. If you call WaitForExit() without timeout you could use something like this function I wrote (based on C# code):
It captures stdout, stderr and exit code. Example usage:
For more info and alternative implementations (in C#) read this blog post.
The examples here are all useful, but didn't completely suit my use case. I didn't want to invoke the command and exit. I wanted to open a command prompt, send input, read the output, and repeat. Here's my solution for that.
Create Utils.CmdManager.cs
Then from PowerShell add the class and use it.
Don't forget to call the
Dispose()
function at the end to clean up the process that is running in the background. Alternatively, you could close that process by running something like$cmd.RunCommand("exit")
Based on Alexander Obersht's answer I've created a function that uses timeout and asynchronous Task classes instead of event handlers. According to Mike Adelson
I couldn't get either of these examples to work with PS 4.0.
I wanted to run
puppet apply
from an Octopus Deploy package (viaDeploy.ps1
) and see the output in "real time" rather than wait for the process to finish (an hour later), so I came up with the following:Credit goes to T30 and Stefan Goßner