"Write-Host","Write-Output"或"[console] :: WriteLine"之间有什么区别?

Sco*_*ham 186 powershell

似乎有许多不同的输出消息的方法.是通过什么东西输出之间的有效差异Write-Host,Write-Output[console]::WriteLine

我还注意到,如果我使用:

write-host "count=" + $count
Run Code Online (Sandbox Code Playgroud)

+被包括在输出.为什么?在写出之前,是否应该对表达式进行求值以生成单个连接字符串?

And*_*ndi 256

Write-Output当您想要在管道中发送数据时,应该使用它,但不一定要在屏幕上显示它.out-default如果没有其他任何东西首先使用它,管道最终会将其写入.Write-Host当你想做相反的事情时应该使用.[console]::WriteLine本质上Write-Host是在幕后做的事情.

运行此演示代码并检查结果.

function Test-Output {
    Write-Output "Hello World"
}

function Test-Output2 {
    Write-Host "Hello World" -foreground Green
}

function Receive-Output {
    process { Write-Host $_ -foreground Yellow }
}

#Output piped to another function, not displayed in first.
Test-Output | Receive-Output

#Output not piped to 2nd function, only displayed in first.
Test-Output2 | Receive-Output 

#Pipeline sends to Out-Default at the end.
Test-Output 
Run Code Online (Sandbox Code Playgroud)

您需要将连接操作括在括号中,以便PowerShell在为参数列表标记之前处理连接Write-Host.

write-host ("count=" + $count)
# or
write-host "count=$count"
Run Code Online (Sandbox Code Playgroud)

BTW - 观看Jeffrey Snover的视频,解释管道的工作原理.回到我开始学习PowerShell时,我发现这是管道工作原理最有用的解释.

  • 有新的指导:尽可能避免使用“Write-Output”。请参阅 https://github.com/PoshCode/PowerShellPracticeAndStyle/issues/46#issuecomment-469449001 > 仅使用 return 来结束执行。> 避免写输出 (...)。相反,当您想让输出更清晰时,只需将输出分配给相关命名的变量即可。并将该变量单独放在一行上以表示显式输出。> Write-Output -NoEnumerate 在 PowerShell 6 上被破坏,并且已经持续了 16 个月或更长时间——没有计划修复它。总之: > 永远不要使用写输出。 (2认同)

KFL*_*KFL 28

除了Andy提到的,还有另一个可能很重要的区别 - 写主机直接写入主机并且不返回任何内容,这意味着您不能将输出重定向到例如文件.

---- script a.ps1 ----
write-host "hello"
Run Code Online (Sandbox Code Playgroud)

现在在PowerShell中运行:

PS> .\a.ps1 > someFile.txt
hello
PS> type someFile.txt
PS>
Run Code Online (Sandbox Code Playgroud)

如图所示,您无法将它们重定向到文件中.对于不小心的人来说,这可能会令人惊讶.

但是如果改为使用write-output,你将获得重定向工作.


Far*_*Bob 15

这是完成写输出等效的另一种方法.只需将您的字符串放在引号中:

"count=$count"
Run Code Online (Sandbox Code Playgroud)

您可以通过运行此实验来确保其与Write-Output的工作方式相同:

"blah blah" > out.txt

Write-Output "blah blah" > out.txt

Write-Host "blah blah" > out.txt
Run Code Online (Sandbox Code Playgroud)

前两个会输出"blah blah"到out.txt,但第三个不会.

"help Write-Output"给出了这种行为的暗示:

此cmdlet通常在脚本中用于在控制台上显示字符串和其他对象.但是,由于默认行为是在管道末尾显示对象,因此通常不必使用cmdlet.

在这种情况下,字符串本身"count = $ count"是管道末尾的对象,并显示.


Dre*_*kes 7

对于 的用法Write-HostPSScriptAnalyzer产生以下诊断信息:

避免使用,Write-Host因为它可能不适用于所有主机,在没有主机时不起作用,并且(PS 5.0 之前)无法抑制、捕获或重定向。相反,使用Write-OutputWrite-VerboseWrite-Information

有关更多信息,请参阅该规则背后的文档。后人节选:

使用的Write-Host,除非在使用命令的与大大气馁Show动词。该Show动词明确表示“在屏幕上显示,没有其他可能性”。

带有Show动词的命令不应用此检查。

Jeffrey Snover 有一篇博客文章Write-Host 被认为有害,他声称Write-Host 几乎总是错误的做法,因为它会干扰自动化并在诊断背后提供更多解释,但以上是一个很好的总结。