mar*_*017 4 powershell hashtable
我有一个函数,我传递一个哈希表.在我想要的功能中1)通过Write-Host在屏幕上显示文本; 2)显示哈希表的内容一次 - 提供通常的两列"名称"/"值"哈希表显示.3)有功能返回$true或$false.
MyFunction $MyHashTable
Run Code Online (Sandbox Code Playgroud)
在功能内:
param (
[hashtable]$TheHashTable
)
# Sundry things here and then:
write-host "Some information to display on-screen`n"
# and then:
$TheHashTable
Run Code Online (Sandbox Code Playgroud)
后者的预期结果如下:
Some information to display on-screen
Name Value
---- -----
a b
c d
Run Code Online (Sandbox Code Playgroud)
并最终:
return $true # If what I'm doing worked; otherwise, $false
Run Code Online (Sandbox Code Playgroud)
如果我按上面所示调用该函数,我会看到通过Write-Host屏幕显示的文本,以及散列表内容的两列显示 - 以及文本True或False屏幕上的内容,具体取决于函数返回的内容.
如果我这样称呼它:
$myResult = MyFunction $MyHashTable
Run Code Online (Sandbox Code Playgroud)
...我捕获函数的返回值$myResult- 但是哈希表内容的显示被抑制.如果我这样做也会被抑制:
if ( (MyFunction $MyHashTable) -eq $true ) {
# do something
} else {
# do something different
}
Run Code Online (Sandbox Code Playgroud)
有办法吗?
True和False的时候Return执行的语句?您的函数生成的任何输出都将沿管道发送.这正是你写的时候会发生的事情:
$TheHashTable
Run Code Online (Sandbox Code Playgroud)
如果你想将这个值写入屏幕而不是管道,你也应该Write-Host像在前面的示例中那样使用,如下所示:
Write-Host $TheHastTable
Run Code Online (Sandbox Code Playgroud)
但是,使用上面的代码,您可能会得到类似以下输出:
PS>$table = @{ "test"="fred";"barney"="wilma"}
PS> write-host $table
System.Collections.DictionaryEntry System.Collections.DictionaryEntry
Run Code Online (Sandbox Code Playgroud)
显然Write-Host不适用您期望的格式,这可以通过使用Out-String如下修复:
PS> $table | Out-String | Write-Host
Run Code Online (Sandbox Code Playgroud)
导致:
Name Value
---- -----
barney wilma
test fred
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4587 次 |
| 最近记录: |