Suppressing return values in PowerShell functions

PSMDTAG:FAQ: How do I supress return values in PowerShell functions?


This was asked in a newgroup with the clarification:



What I mean is:
When you call a function Foo that returns a bool, PS will write ‘True’ or ‘False’ to the screenby default. Is there anyway to get it to stop writing those return values?


Let’s illustrate the issue:


PS> function test {return $true}
PS> test
True
PS>


First let me clarify what is going on here by answering another FAQ:


PSMDTAG:FAQ: What is the difference between Write-Output $x, return $x and $x?


$x and Write-Output $x are exactly the same.  Both of these emit $x to the output stream.  (NOTE: “Write-Output” will show up in RC2 – in RC1 it is called Write-Object.)  By default, the CONSOLE HOST displays anything that goes to the Output Stream on the CONSOLE.  The engine merely makes these objects available to the host, it is the host’s decision to do what they will with them (e.g. the Exchange 2007 admin GUI takes these objects and does something completely different with them [they bind them to property sheets and display them]).


Return $x is the same as Write-Output $x; Return .  We support this syntax because it is used so widely in other environments.


PS> function test1
>> {  “test1”
>>    write-Output “test2”
>>    return “test3”
>> }
>>
PS> test1
test1
test2
test3
PS> $x = test1
PS> $x.length
3
PS> $x[0]
test1
PS> $x[1]
test2
PS> $x[2]
test3
PS>


Now back to the original question – can this be supressed?  There are a number of ways to do this but they all entail one or another versions of the following strategy: Don’t let the Output stream get to the host.  Here are some examples:


PS> #Refresher – this is what we don’t want to happen
PS> test
True
PS> # We can assign the output to a variable
PS> $null = test
PS> # we can cast the expression to void
PS> [void](test)
PS> # We can pipel the objects to Out-Null
PS> test |out-null


Jeffrey Snover [MSFT]
Windows PowerShell/Aspen Architect
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx