PowerShell 中的 Write-Host 和 Write-Output 有什么区别?
喜欢...
Write-Host "Hello World";
Write-Output "Hello World";
简而言之,Write-Host
写入控制台本身。将其视为 VBScript 中的 MsgBox。另一方面,Write-Output
写入管道,因此下一个命令可以接受它作为其输入。您不需要使用 Write-Output
来编写对象,因为 Write-Output
是为您隐式调用的。
PS> Get-Service
将与以下内容相同:
PS> Get-Service | Write-Output
Write-Output 将输出发送到管道。从那里它可以通过管道传输到另一个 cmdlet 或分配给一个变量。 Write-Host 将其直接发送到控制台。
$a = 'Testing Write-OutPut' | Write-Output
$b = 'Testing Write-Host' | Write-Host
Get-Variable a,b
输出:
Testing Write-Host
Name Value
---- -----
a Testing Write-OutPut
b
如果您没有通过将输出分配给变量或通过管道将其传递给另一个命令来告诉 Powershell 如何处理管道的输出,那么它将被发送到 out-default,这通常是控制台,因此最终结果看起来相同.
Write-Output
通过管道将数据作为对象发送。在 Questions 示例中,它只会传递一个字符串。
Write-Host
取决于主机。在控制台中 Write-Host
本质上是在做 [console]::WriteLine
。有关详细信息,请参阅 this。
Write-Ouput
发送对象。这次它是一个字符串,但通常它会发送对象,并且通常不需要使用,因为它是输出结果/数据的默认方式:)
Write-Host 和 Write-Output 之间的另一个区别:
Write-Host 在屏幕上显示消息,但不会将其写入日志
Write-Output 将消息写入日志,但不会在屏幕上显示。
并且 Write-Host 被认为是有害的。您可以在 Write-Host Considered Harmful 中查看详细说明。
Write-Output
会在屏幕上显示消息。所以我不确定“Write-Output 将一条消息写入日志,但它没有在屏幕上显示”是什么意思。 ?
您可以通过以下示例了解两个 cmd 之间的区别:
Write-host "msgtxt" | Get-Service
在上面运行时,您将获得输出为“msgtxt”
Write-output "msgtxt" | Get-Service
在上面运行时,您将收到一个错误,因为 msgtxt 不是任何服务的名称。(在理想情况下)(因为您将其写入管道并且它作为输入传递给 Get-Service)