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
- Ensure the display of hashtable content, no matter how the function is called;
- In any case, suppress the on-screen display of
TrueandFalsewhen theReturnstatement is executed?
Any output generated by your function will be sent down the pipeline. This is exactly what happens when you write:
If you want to write this value to the screen instead of the pipeline you should also use
Write-Hostlike you do earlier in the example like so:However using the code above you will probably get something like the following output:
Apparently
Write-Hostdoes not apply the formatting you expect, this can be fixed by usingOut-Stringlike so:resulting in: