本文介绍了写主机和写输出的结果有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 PowerShell 的新手,在编写一些代码时,我遇到了这件事.当我使用 Write-HostWrite-Output 来执行相同的查询时,我得到了不同的结果:

I am new to PowerShell and while doing some code I came through this thing.While I use Write-Host and Write-Output to perform the same query, I get different results:

PS> Write-Output $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.0.10586.117
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.10586.117
CLRVersion                     4.0.30319.17929
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

对比

PS> Write-Host $PSVersionTable
System.Collections.DictionaryEntry System.Collections.DictionaryEntry System.Collections.DictionaryEntry System.Collections.DictionaryEntry System.Collections.DictionaryEntry System.Collections.DictionaryEntry System.Collections.DictionaryEntry System.Collections.DictionaryEntry System.Collections.DictionaryEntry

推荐答案

重要区别:

Write-output 将一个对象写入管道,因此下一个命令可以接受它作为输入.而Write-host只是直接写入控制台.

Write-output writes an object to the pipeline, so the next command can accept it as it's input.While Write-host just write directly to the console.

在你的例子中

Write-Output 将对象写入管道,Out-Default(隐藏在管道的末尾)将在表格或列表中显示对象值.

Write-Output will write the object to the pipeline, and Out-Default (Hidden at the end of the pipeline) will display the object values in either a table or a list.

Write-Host 直接写入控制台,而不是在管道末端使用默认的 cmdlet Out-default.换句话说,Write-Host 不会向管道写入任何内容,只会向控制台显示他看到的内容.这就是您可以将 -foregroundcolor 等参数添加到 Write-Host cmdlet 而不能添加到 Write-output cmdlet 的原因.

Write-Host writes directly to the console instead of using the default cmdlet Out-default in the end of the pipeline. In other words, Write-Host does not write anything to the pipeline, only displays what he sees to the console..This is why you can add parameters like -foregroundcolor to the Write-Host cmdlet, but not to the Write-output cmdlet.

Write-Host 在调试时很有用,您需要以不同的颜色显示文本.

Write-Host is useful when debugging and you need to display text in diffrent colors.

你可以用

Write-Output "Hello World" | Get-Member

我们可以看出这是一个 System.String 对象.

We can se that this is a System.String Object.

如果我们运行:

Write-Host "Hello World" | Get-Member

我们得到一个错误:gm :您必须为 Get-Member cmdlet 指定一个对象...

We get an error:gm : You must specify an object for the Get-Member cmdlet ...

这篇关于写主机和写输出的结果有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 21:28
查看更多