As documented PowerShell functions return all non-captured output to the caller. If the caller doesn't do anything with the returned value PowerShell automatically passes it to Out-Default
, which then forwards it to Out-Host
(see this article written by Don Jones).
Using redirection operators on the return value inside the function effectively suppresses the return value so that the function wouldn't return anything.
If you have a function like this:
function testit {
return $true
}
and call it by itself:
testit
PowerShell implicitly does this:
testit | Out-Default
which effectively becomes
testit | Out-Host
If you capture the return value in a variable
$thistest = testit
the value gets stored in the variable without anything being displayed on the console.
If you redirect the output or pipe it into Out-Null
testit >$null
testit | Out-Null
the return value is discarded and nothing is displayed on the console.
If you want to prevent PowerShell's default behavior of passing uncaptured output at the end of a pipeline to Out-Host
you can do so by overriding Out-Default
like this:
filter Out-Default { $_ | Out-Null }
or (as @PetSerAl pointed out in the comments) like this:
filter Out-Default {}
However, beware that this modification disables Out-Default
for everything in the current scope until you remove the filter again. If you do for instance a Get-ChildItem
while the filter is active nothing will be displayed unless you explicitly write the output to the host console:
Get-ChildItem | Out-Host
You remove the filter like this:
Remove-Item function:Out-Default
return $true
or just$true
? – Arviefunction test { $true }; $x = test
has no on-screen output, and it keeps the return value in$x
– Kymricreturn $true
to showTrue
in the console. – Amey