"Write-Host"、"Write-Output"和"[console]::WriteLine"有什么区别?

19 浏览
0 Comments

"Write-Host"、"Write-Output"和"[console]::WriteLine"有什么区别?

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

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

write-host "count=" + $count

+会包含在输出中。为什么会这样?该表达式不应该在写出之前被评估为产生一个单一的连接字符串吗?

admin 更改状态以发布 2023年5月20日
0
0 Comments

除了Andy提到的外,还有一个可能很重要的区别--write-host直接写入主机并返回空,意味着你无法将输出重定向到一个文件等等。\n\n

---- script a.ps1 ----
write-host "hello"

\n\n现在在PowerShell中运行:\n\n

PS> .\a.ps1 > someFile.txt
hello
PS> type someFile.txt
PS>

\n\n如上所示,你无法将它们重定向到一个文件中。这对于不小心的人可能很惊讶。\n\n但如果改用write-output,你将得到预期的重定向功能。

0
0 Comments

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 时,我发现这是关于管道如何工作的最有用的解释。

0