How do I redirect Console Output to PowerShell Output within a module?

918 views Asked by At

If I'm writing a binary PowerShell module and I happen to use a .NET library that writes to STDOUT (Console.Out) -- is there a recommended approach to reroute the console output to PowerShell's Output stream?

I can intercept the Console.Out by setting my own TextWriter via Console.SetOut(...) and then do something with it (i.e. I can buffer the output with a StringWriter and write it all out at some future point, or I can write a custom TextWriter that sends all Write commands to PowerShell's WriteObject).

My question is really, is there some standard or recommended practice for doing this or some built-in tools in the PowerShell library already?

2

There are 2 answers

0
E Bekker On BEST ANSWER

I asked the question of the PS team via GitHub and the general response was that the TextWriter-to-WriteObject approach was a reasonable approach: https://github.com/PowerShell/PowerShell/issues/4849

1
John Donnelly On

If you want to output to the pipeline use WriteObject(). WriteInformation(), WriteDebug(), WriteWarning() gets a message (string) to the host.