Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 2) display the contents of the hashtable one time -- to provide the usual two-column "Name" / "Value" hashtable display. 3) Have the function return $true or $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.

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. It is also suppressed if I do this:

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


Is there a way to

  1. Ensure the display of hashtable content, no matter how the function is called;
  2. In any case, suppress the on-screen display of True and False when the Return statement is executed?
like image 652
marst12017 Avatar asked Nov 12 '12 23:11

marst12017


1 Answers

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 $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:

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

resulting in:

Name                           Value
----                           -----
barney                         wilma
test                           fred
like image 93
Bas Bossink Avatar answered Nov 10 '22 23:11

Bas Bossink