Piping to Out-Null is the equivalent to redirecting to $null but invokes the pipeline and can be up to forty times slower.
Powershell in Action by B. Payette and R. Siddaway
There are times when you want/need to null the output in your powershell script. One of the most frequent use cases is when you do some operation that provides some service output.
When you are doing it inside the function it might ( and usually will) mess up your return object. To avoid this we need to use some output “nulling” technic.
Out-Null
By default all of the output in PowerShell is sent to Out-Default
. When you are piping object(or collection of objects) via pipeline each object is processed in sequential order – one at a time. This is called streaming behavior, objects are output from pipeline as soon as they become available.
As it is outlined in help for Out-Null
, it is designed to “Delete output instead of sending it down the pipeline.”
Get-Process | Out-Null
Every process object is passed via pipeline and is nulled(deleted) after that.
Let’s use Measure-Command
to identify performance statistics:
Measure-Command {Get-Process | Out-Null}
As you can see from the image above it too 18.2 milliseconds
to delete each process object using Out-Null
cmdlet.
Redirecting to $null (>> $null)
$null
is a special object in PowerShell and has a lot of use cases and functionality.
Please refer to great article about $null
– Powershell: Everything you wanted to know about $null by @KevinMarquette
PowerShell is shell and it supports output redirecting operators – >
and >>
.
Main difference between >
and >>
is that last one will append output if you will send it to file while the other one will rewrite it.
As in PowerShell $null
is constant value and we cannot rewrite or append to it we will use >
operator (because it is shorter).
Measure-Command {Get-Process > $null}
As you can see it took 4.5 milliseconds
.
Summary
Out-Null
is more “PowerShellish” way of “nulling” output as you are using pipeline and specifically designed cmdlet for this.
BUT if performance is your main priority – go with > $null
. Plus it is shorter to type – 7 symbols vs 10.
Thanks a lot for reading. Please leave you thoughts and/or comments in the comments section below.