"Write-Host"、"Write-Output"和"[console]::WriteLine"有什么区别?
"Write-Host"、"Write-Output"和"[console]::WriteLine"有什么区别?
有很多不同的方法来输出消息。通过Write-Host
、Write-Output
或[console] :: WriteLine
输出某些内容之间的有效区别是什么?
我还注意到,如果我使用:
write-host "count=" + $count
+
会包含在输出中。为什么会这样?该表达式不应该在写出之前被评估为产生一个单一的连接字符串吗?
admin 更改状态以发布 2023年5月20日
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 解释管道如何工作的 视频。回到我开始学习 PowerShell 时,我发现这是关于管道如何工作的最有用的解释。