简体   繁体   English

PowerShell 默认使用 Write-Host 还是 Write-Output

[英]Does PowerShell use Write-Host or Write-Output by default

When I type "my text" on a line by itself, the text is output to the console, but is that using Write-Host or Write-Output by default (and how can I see that - I mean, I tried using | Get-Member to get a clue but was not sure)?当我在一行上单独输入"my text"时,文本会输出到控制台,但是默认情况下是使用Write-Host还是Write-Output (我怎么能看到 - 我的意思是,我尝试使用| Get-Member获得线索但不确定)?

The reason that I'm asking is that I'm aware of the known issues with Write-Host breaking sequential output in a script that has pipeline commands nearby.我问的原因是我知道 Write-Host 会破坏附近具有管道命令的脚本中的顺序输出的已知问题。

So, I did a small test to figure this one out.所以,我做了一个小测试来解决这个问题。 Out-Host and Write-Host, cannot be redirected to any stream whatsoever. Out-Host 和 Write-Host 不能重定向到任何流。 This is how they work, they simply write to whatever is the default calling stream.这就是它们的工作方式,它们只是写入默认调用流。

Using this logic,使用这个逻辑,

"string1" | Out-host *>$null

will give the output as "string1", since it cannot be re-directed.将输出作为“string1”,因为它不能被重定向。 But,但,

"string1" *>$null

will display no output, hence proving, writing any text is the same as passing it to the Write-Output cmdlet:将不显示输出,因此证明,写入任何文本与将其传递给 Write-Output cmdlet 是相同的:

# All are same
"string"
"string" | Write-Output
Write-Output "string"

There are several methods of displaying text in powershell.在 powershell 中有多种显示文本的方法。 The write-host displays the text itself in the console. write-host在控制台中显示文本本身。 It is host dependent.它依赖于主机。 Next, write-output writes output from a pipeline, so the next command can receive it.接下来, write-output将输出从管道中写入,以便下一个命令可以接收它。 It's not necessary it will display text every time.没有必要每次都显示文本。 [Console]::WriteLine is quite same like write-host . [Console]::WriteLinewrite-host非常相似。 And Out-Default sends the output to the default formatter and to the default output cmdlet. Out-Default将输出发送到默认格式化程序和默认输出 cmdlet。 It is automatically added by powershell itself at the end of every pipeline.它由 powershell 本身自动添加到每个管道的末尾。 If the input object is not string it decides what to do.如果输入对象不是字符串,它决定做什么。 So, it is Out-Default which does this.因此,这是Out-Default执行此操作。

Write-output.写输出。

write-host hi | measure | % count
hi
0

write-output hi | measure | % count
1

'hi' | measure | % count             
1

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

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