Discarding Results

by Sep 11, 2014

All PowerShell Versions

Since PowerShell returns anything that commands leave behind, it is particularly important in PowerShell scripts to discard any result that you do not want to return.

There are many way to achieve this, and here are the two most popular. Note that both lines try and create a new folder on your drive C:. New-Item would return the folder object, but if all you want is create a new folder, then you may want to discard the result:

$null = New-Item -Path c:\newfolderA -ItemType Directory

New-Item -Path c:\newfolderB -ItemType Directory | Out-Null

So which approach is better? Definitely the first one. Piping unwanted results to Out-Null is expensive and takes about 40x the time. You won't notice on single calls, but if this happens within a loop, it may become significant.

So better get into the habit of using $null rather than Out-Null!

Twitter This Tip! ReTweet this Tip!