[英]Powershell: hashtable content not displayed within a function
I have a function to which I pass a hashtable. 我有一个函数,我传递一个哈希表。 Within the function I want to 1) Display text on-screen via Write-Host;
在我想要的功能中1)通过Write-Host在屏幕上显示文本; 2) display the contents of the hashtable one time -- to provide the usual two-column "Name" / "Value" hashtable display.
2)显示哈希表的内容一次 - 提供通常的两列“名称”/“值”哈希表显示。 3) Have the function return
$true
or $false
. 3)让函数返回
$true
或$false
。
MyFunction $MyHashTable
Within the function: 在功能内:
param (
[hashtable]$TheHashTable
)
# Sundry things here and then:
write-host "Some information to display on-screen`n"
# and then:
$TheHashTable
The expected result of the latter is something like: 后者的预期结果如下:
Some information to display on-screen
Name Value
---- -----
a b
c d
And eventually: 并最终:
return $true # If what I'm doing worked; otherwise, $false
If I call the function as shown above, I see text displayed via Write-Host
on-screen, plus the two-column display of the hashtable's contents -- and the text True
or False
on-screen, depending on what the function returns. 如果我按上面所示调用该函数,我会在屏幕上看到通过
Write-Host
显示的文本,以及哈希表内容的两列显示 - 以及屏幕上的文本True
或False
,具体取决于函数返回的内容。
If I call it this way: 如果我这样称呼它:
$myResult = MyFunction $MyHashTable
... I capture the return value of the function in $myResult
-- but the display of the hash table's content is suppressed . ...我在
$myResult
捕获函数的返回值 - 但是哈希表内容的显示被抑制 。 It is also suppressed if I do this: 如果我这样做也会被抑制:
if ( (MyFunction $MyHashTable) -eq $true ) {
# do something
} else {
# do something different
}
Is there a way to 有办法吗?
True
and False
when the Return
statement is executed? Return
语句时, 禁止屏幕显示True
和False
? Any output generated by your function will be sent down the pipeline. 您的函数生成的任何输出都将沿管道发送。 This is exactly what happens when you write:
这正是你写的时候会发生的事情:
$TheHashTable
If you want to write this value to the screen instead of the pipeline you should also use Write-Host
like you do earlier in the example like so: 如果你想将这个值写入屏幕而不是管道,你也应该使用
Write-Host
就像你在前面的示例中所做的那样:
Write-Host $TheHastTable
However using the code above you will probably get something like the following output: 但是,使用上面的代码,您可能会得到类似以下输出:
PS>$table = @{ "test"="fred";"barney"="wilma"}
PS> write-host $table
System.Collections.DictionaryEntry System.Collections.DictionaryEntry
Apparently Write-Host
does not apply the formatting you expect, this can be fixed by using Out-String
like so: 显然
Write-Host
不应用你期望的格式,这可以通过使用Out-String
来修复,如下所示:
PS> $table | Out-String | Write-Host
resulting in: 导致:
Name Value
---- -----
barney wilma
test fred
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.