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
True
and False
when the Return
statement is executed?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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With