在Powershell中,Write-Host会调用管道对象上的任何方法

时间:2017-08-01 05:37:53

标签: powershell powershell-v2.0

Write-Host对管道数据/对象进行了哪些操作?

在我的情况下,如果我Intent intent = new Intent(getActivity(), YourActivity.class); String name = "Transporter"; intent.putExtra("name", name); startActivity(intent); ,它将输出一个对象表,如果我try { Intent intent = getIntent(); String name = intent.getStringExtra("name"); } catch(Exception e) { e.printStackTrace(); } ,它将输出实际的XML。当我<img to <amp-img时,它与Write-Host产生的输出不同。因此,上面的问题。

2 个答案:

答案 0 :(得分:2)

应该是因为ToString()是from the underlying PSObject,给你一个对象的字符串表示。 因此,如果键入对象,结果会更改。 然后ToString()将取决于你输入的内容。 Write-Host将调用ToString()。

我尝试了3种方案来区分可观察性: Last scenario is from Shay Levy's post.

$untyped = Get-Content 'some.xml'
$untyped.ToString()
$pureDoc | Write-Host 

[xml]$typed =  Get-Content 'some.xml'
$typed.ToString()
$typed | Write-Host 

$pso = new-object psobject -property @{ name = 'bob'; job = 'janitor' }
$pso | add-member scriptmethod ToString { 'he is a {0}, he is' -f $this.job } -force 
$pso.ToString()
$pso | Write-Host

输出是:

System.Object[]
[XML omitted for brevity]
#document
#document
he is a janitor, he is
he is a janitor, he is

你看到Write-Host如何返回ToString()的实现?

答案 1 :(得分:2)

Write-Host会做一些通常违反直觉或不是最好的做事方式的事情,所以我不鼓励你使用它。相反,请查看Write-VerboseWrite-Output(或只是尝试Get-Help Write-*查看所有可能性)。

<强> INPUT:

Write-Host以可能意外的方式更改输入。输出stringint或其他熟悉的类型时,它将输出该输入的内容。但是,正如我确定你看到并且感到困惑,有些类型Write-Host不会输出内容,相反,它只会输出输入的类型。在大多数情况下,这是无用的。

<强>输出:

Write-Host输出的格式与自己编写输入的格式相同,或者在函数中写入return。这三个可以等效地用于字符串类型,例如:

$str

Write-Host $str

return $str #in context of a function

请再次注意,它们与string类型以及其他类型相同,但Write-Host可能会以奇怪的方式操纵其他类型的输入。

一般情况下,不鼓励使用Write-Host。要调试/输出到控制台,请使用Write-Verbose。要输出到管道或输出函数,请自行编写变量。这将输出我们在powershell中使用的漂亮的字典样式格式:

PS C:\Windows\system32> $dict

Name                           Value
----                           -----
key                            value
{test, test2}                  1

与:相比:

PS C:\Windows\system32> write-host $dict
System.Collections.DictionaryEntry System.Collections.DictionaryEntry