2

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   
2
  • 3
    "that gives me an empty stream" - are you trying to read from it? It's an output stream, you're supposed to write to it Commented Oct 6, 2015 at 20:05
  • I am trying to write to it. I read from it and did a .Length to see what was in it at the time after I got it. Since the screen was covered in basic pipeline output, I figured it shouldn't be empty. I don't know if it makes a difference that I'm using the ISE, though. Commented Oct 6, 2015 at 20:15

1 Answer 1

2

(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)

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately this is the same as Write-Host( ). What we want is Write-Output( ). That way you can use it to stream data to the next pipe... or even from a remote PSSession object. I'm not entirely sure that the output stream is actually a stream at all, since it's dealing with native c# objects. So perhaps a function [Pipe-Stream] would be desirable that would read a System.IO.Stream and call Write-Output every n bytes...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.