There are four ways to suppress an output:
- Redirection to
$nullvariablePS C:\> 1; $(2; return) > $null; 3 1 3 - Piping to
Out-NullcmdletPS C:\> 1; $(2; return) | Out-Null; 3 1 2 - Casting to
[void]typePS C:\> 1; [void]$(2; return); 3 1 2 - Assignment to
$nullvariablePS C:\> 1; $null = $(2; return); 3 1 2
All four cases are expected to be equivalent.
Why redirection to $null behaves different? Have I faced a bug?
An additional example
This example shows unexpected behavior of > $null command in PS 2.0:
PS C:\> 1; $(Write-Output 2; Write-Host 3; return; Write-Host 4) > $null; 5
1
3
5
return command acts as if it exits from some nested context (though there is no command which creates it), stops $() expression execution and then continues the execution (when it shouldn't) in the current context to the Write-Output 5 command.
BEHAVIOR EXPLANATIONS
(from wOxxOm's answer)
- in PS 1.0 and 2.0
> $nulloperation is executed before$()expression and suppresses its output;returncommand does not exit from the current context (considered a BUG), but stops$()expression execution - in PS 3.0 and newer
> $nulloperation is executed before$()expression and suppresses its output in all cases;returncommand exits from the current context completely | Out-Null,[void],$null =operations are executed after$()expression and suppress its output if there is noreturncommand in it;returncommand exits from the current context completely
SUMMARY
Different methods for suppressing command output:
... > $nullredirection to$nullvariable
Bug in PS 1.0 and 2.0. In PS 3.0+ output may differ from other methods... | Out-Nullpiping toOut-Nullcmdlet
Performance issues *[void]...casting to[void]type
Advisable$null = ...assignment to$nullvariable
Advisable