简体   繁体   English

如何在 Powershell 中获取输出流?

[英]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.我想知道是否有可能获得引用 Powershell 控制台窗口(在 Powershell 中)的流,假设存在一个。 For example, in C# .NET it would be done simply by Console.OpenStandardOutput() .例如,在 C# .NET 中,只需通过Console.OpenStandardOutput()即可完成。 Is there an equivalent in Powershell? 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.我要做的是创建一个System.IO.BinaryWriter来写入它,而不是使用 Write-Host 等,主要用于实验。

I've tried [Console]::OpenStandardOutput() , but that gives me an empty stream, making me think a different one is in use for Powershell.我试过[Console]::OpenStandardOutput() ,但这给了我一个空流,让我认为 Powershell 正在使用不同的流。

I'm working with Powershell V5.0:我正在使用 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.) 注意: PowerShell ISE 不使用控制台,因此写入流也不会产生任何影响。)

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 ):在基于控制台的主机(即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)您应该看到字符串Test被写入屏幕(以及尾随换行符)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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