有许多不同的方法可以输出消息。通过Write-Host、Write-Output或[console]::WriteLine输出内容之间的有效区别是什么?
我还注意到,如果我使用:
write-host "count=" + $count+将包含在输出中。为什么会这样呢?在写出表达式之前,不应该计算该表达式以生成单个连接字符串吗?
发布于 2012-01-06 17:15:47
如果要在管线中发送数据,但不一定要在屏幕上显示数据,则应使用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 您需要将连接操作括在括号中,以便PowerShell在标记Write-Host的参数列表之前处理连接,或者使用字符串插值
write-host ("count=" + $count)
# or
write-host "count=$count"顺便说一句--观看Jeffrey Snover的这篇video,解释管道是如何工作的。回到我开始学习PowerShell的时候,我发现这是对管道如何工作的最有用的解释。
发布于 2013-05-23 09:02:45
除了Andy提到的,还有一个很重要的区别-- write-host直接写入主机,不返回任何东西,这意味着你不能重定向输出,例如,到文件。
---- script a.ps1 ----
write-host "hello"现在在PowerShell中运行:
PS> .\a.ps1 > someFile.txt
hello
PS> type someFile.txt
PS>如图所示,您不能将它们重定向到文件中。对于不小心的人来说,这可能会让人感到惊讶。
但是,如果切换到使用write-output,您将获得预期的重定向工作。
发布于 2013-08-31 09:50:42
这里有另一种实现写输出等价物的方法。只需将字符串放在引号中:
"count=$count"通过运行此实验,您可以确保这与Write-Output的工作方式相同:
"blah blah" > out.txt
Write-Output "blah blah" > out.txt
Write-Host "blah blah" > out.txt前两个将输出"blah blah“到out.txt,但第三个不会。
"help Write-Output“给出了此行为的提示:
此cmdlet通常在脚本中使用,以便在控制台上显示字符串和其他对象。但是,由于默认行为是在管道末尾显示对象,因此通常不需要使用cmdlet。
在本例中,字符串本身"count=$count“是管道末尾的对象,并显示出来。
https://stackoverflow.com/questions/8755497
复制相似问题