Clear captured output/return value in a Powershell function

powershell

Solution

Pipe output to `Out-Null`, redirect output to `$null`, or prefix the function calls with `[void]`:

$myArray.Add("Hello") | Out-Null

or

$myArray.Add("Hello") >$null

or

[void]$myArray.Add("Hello")

Problem

Is there a way to clear the return values inside of a function so I can guarantee that the return value is what I intend? Or maybe turn off this behaviour for the function? In this example, I expect the return value to be an ArrayList containing ("Hello", "World") ``` function GetArray() { # $AutoOutputCapture = "Off" ? $myArray = New-Object System.Collections.ArrayList $myArray.Add("Hello") $myArray.Add("World") # Clear return value before returning exactly what I want? return $myArray } $x = GetArray $x ``` However, the output contains the captured value from the Add operations. ``` 0 1 Hello World ``` I find this "feature" of Powershell very annoying because it makes it really easy to break your function just by calling another function, which you didn't know returned a value. Update I understand there are ways to prevent the output from being captured (as described in one of the answers below), but that requires you to know that a function actually returns a value. If you're calling another Powershell function, it can be, in the future, someone changes this function to return a value, which will then break your code.

Original source