“Write-Host"、“Write-Output"或“[console]::WriteLine"之间有什么区别? [英] What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

查看:61
本文介绍了“Write-Host"、“Write-Output"或“[console]::WriteLine"之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有多种不同的方式来输出消息.通过 Write-HostWrite-Output[console]::WriteLine 输出内容之间的有效区别是什么?

There are a number of different ways to output messages. What is the effective difference between outputting something via Write-Host, Write-Output, or [console]::WriteLine?

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

I also notice that if I use:

write-host "count=" + $count

+ 包含在输出中.为什么?在写出之前,不应该对表达式求值以生成单个连接字符串吗?

The + gets included in the output. Why's that? Shouldn't the expression be evaluated to produce a single concatenated string before it gets written out?

推荐答案

Write-Output 当你想在管道中发送数据,但不一定想在管道上显示它时,应该使用屏幕.如果没有其他东西首先使用它,管道最终会将其写入 out-default.

Write-Output should be used when you want to send data on in the pipe line, but not necessarily want to display it on screen. The pipeline will eventually write it to out-default if nothing else uses it first.

Write-Host 当你想做相反的事情时应该使用它.

Write-Host should be used when you want to do the opposite.

[console]::WriteLine 本质上是 Write-Host 在幕后所做的.

[console]::WriteLine is essentially what Write-Host is doing behind the scenes.

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

Run this demonstration code and examine the result.

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 

您需要将连接操作括在括号中,以便 PowerShell 在标记 Write-Host 的参数列表之前处理连接,或使用字符串插值

You'll need to enclose the concatenation operation in parentheses, so that PowerShell processes the concatenation before tokenizing the parameter list for Write-Host, or use string interpolation

write-host ("count=" + $count)
# or
write-host "count=$count"

顺便说一句 - 观看这个 视频 解释了管道的工作原理.当我开始学习 PowerShell 时,我发现这是对管道如何工作的最有用的解释.

BTW - Watch this video of Jeffrey Snover explaining how the pipeline works. Back when I started learning PowerShell I found this to be the most useful explanation of how the pipeline works.

这篇关于“Write-Host"、“Write-Output"或“[console]::WriteLine"之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆