gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:13:03 25 4
gpt4 key购买 nike

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

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

write-host "count=" + $count

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

最佳答案

当您想在管道中发送数据,但不一定想将其显示在屏幕上时,应使用

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"

顺便说一句 - 观看此 video Jeffrey Snover 解释管道的工作原理。当我开始学习 PowerShell 时,我发现这是对管道工作原理最有用的解释。

关于powershell - "Write-Host"、 "Write-Output"或 "[console]::WriteLine"之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8755497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com