简体   繁体   中英

How Can I Get the Output Stream in Powershell?

I'm wanting to know if it's possible to get the stream that refers to the Powershell console window (in Powershell), assuming one exists. For example, in C# .NET it would be done simply by Console.OpenStandardOutput() . Is there an equivalent in Powershell?

What I'm looking to do is create a System.IO.BinaryWriter to write to it instead of using Write-Host or the like, mostly for experimentation.

I've tried [Console]::OpenStandardOutput() , but that gives me an empty stream, making me think a different one is in use for Powershell.

I'm working with Powershell V5.0:

Major  Minor  Build  Revision
-----  -----  -----  --------
5      0      10240  16384   

( Note: PowerShell ISE doesn't use the console, so writing to the stream also won't have any effect.)

Trying to read from the standard output stream won't get you anywhere, it's meant for writing stuff to.

Neither will inspecting the length, as the standard output writer will immediately pick up any input and write it to the screen buffer.

Try this in a console-based host (ie. powershell.exe ):

$TestBytes = "Test`n".ToCharArray() -as [byte[]]
$OutStream = [console]::OpenStandardOutput()
$OutStream.Write($TestBytes,0,$TestBytes.Length)

You should see that the string Test is written to the screen (along with a trailing newline)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM