PowerShell Return behavior in PowerShell Gotcha! Ignoring unwanted output

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Inspired by

function bar {
 [System.Collections.ArrayList]$MyVariable = @()
 $MyVariable.Add("a") | Out-Null
 $MyVariable.Add("b") | Out-Null
 $MyVariable
}

The Out-Null is necessary because the .NET ArrayList.Add method returns the number of items in the collection after adding. If omitted, the pipeline would have contained 1, 2, "a", "b"

There are multiple ways to omit unwanted output:

function bar
{
    # New-Item cmdlet returns information about newly created file/folder
    New-Item "test1.txt" | out-null
    New-Item "test2.txt" > $null
    [void](New-Item "test3.txt")
    $tmp = New-Item "test4.txt"
}

Note: to learn more about why to prefer > $null, see [topic not yet created].



Got any PowerShell Question?