PowerShell: Function doesn't have proper return value

I've found the answer here: http://martinzugec.blogspot.hu/2008/08/returning-values-from-fuctions-in.html

Functions like this:

Function bar {
 [System.Collections.ArrayList]$MyVariable = @()
 $MyVariable.Add("a")
 $MyVariable.Add("b")
 Return $MyVariable
}

uses a PowerShell way of returning objects: @(0,1,"a","b") and not @("a","b")

To make this function work as expected, you will need to redirect output to null:

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

In our case, the function has to be refactored as suggested by Koliat.


An alternative to adding Out-Null after every command but the last is doing this:

$i = (Test-Diff $Dir1 $Dir2 | select -last 1)

PowerShell functions always return the result of all the commands executed in the function as an Object[] (unless you pipe the command to Out-Null or store the result in a variable), but the expression following the return statement is always the last one, and can be extracted with select -last 1.