【问题标题】:Powershell: hashtable content not displayed within a functionPowershell:哈希表内容未在函数中显示
【发布时间】:2012-11-01 10:37:18
【问题描述】:

我有一个传递哈希表的函数。在我想要的功能中 1)通过 Write-Host 在屏幕上显示文本; 2) 一次显示哈希表的内容——提供通常的两列“名称”/“值”哈希表显示。 3) 让函数返回$true$false

MyFunction $MyHashTable


函数内:

param (
    [hashtable]$TheHashTable
)
#  Sundry things here and then:
write-host "Some information to display on-screen`n"
#  and then:
$TheHashTable


后者的预期结果是这样的:

Some information to display on-screen

Name    Value
----    -----
a       b
c       d


最终:

return $true #  If what I'm doing worked; otherwise, $false


如果我调用如上所示的函数,我会在屏幕上看到通过 Write-Host 显示的文本,以及哈希表内容的两列显示 -- 文本 @屏幕上的 987654328@ 或 False,具体取决于函数返回的内容。

如果我这样称呼它:

$myResult = MyFunction $MyHashTable


...我在$myResult 中捕获了函数的返回值——但是哈希表内容的显示被抑制。如果我这样做,它也会被抑制:

if ( (MyFunction $MyHashTable) -eq $true ) {
    #   do something
} else {
    #   do something different
}


有没有办法

  1. 确保哈希表内容的显示,无论函数如何调用;
  2. 在任何情况下,当Return 语句执行时,抑制屏幕上显示TrueFalse

【问题讨论】:

    标签: powershell hashtable


    【解决方案1】:

    您的函数生成的任何输出都将沿管道发送。这正是你写作时发生的事情:

    $TheHashTable
    

    如果您想将此值写入屏幕而不是管道,您还应该使用Write-Host,就像您之前在示例中所做的那样:

    Write-Host $TheHastTable
    

    但是使用上面的代码,您可能会得到如下输出:

    PS>$table = @{ "test"="fred";"barney"="wilma"}
    PS> write-host $table
    System.Collections.DictionaryEntry System.Collections.DictionaryEntry
    

    显然Write-Host 没有应用您期望的格式,这可以通过使用Out-String 来解决,如下所示:

    PS> $table | Out-String | Write-Host
    

    导致:

    Name                           Value
    ----                           -----
    barney                         wilma
    test                           fred
    

    【讨论】:

    • 像宣传的那样工作。谢谢。我真的开始喜欢这个网站了。 :)
    猜你喜欢
    • 2022-11-23
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2015-11-02
    • 2021-03-02
    相关资源
    最近更新 更多