Search code examples
powershellreturn

Why does powershell collect uncaptured values and returns it as an array


The following code, although I would think should return a single value, returns an array.

function Do-Something {
    123
    return 456
}

(Do-Something).GetType() # will say Object[]

I learned that if I want to avoid this I have to pipe the unwanted values to Out-Null like so

function Do-Something {
    123 | Out-Null
    return 456
}

However, I couldn't find any reasoning behind why PowerShell is implemented this way. I find that this can lead to nasty and silent bugs if you forget that something has a return value that you did not capture. Could someone explain when this could come in handy? Also is it possible to force powershell not to collect all uncaptured variables in an array?


Solution

  • PowerShell emits the output of all statements in a script or function into the output pipe because it's a shell and that's how shells work. The return statement is somewhat regrettable in that functions don't return objects, they write objects into the pipeline. Being able to terminate the execution of a function is necessary but we probably should have called it something else. The ability to simply emit objects makes simple scripts simpler because there is no need for explicit output statements or returns. Does it sometimes cause problems - yes, sometimes it does. Consequently, for classes, as introduced in V5, we went with more traditional programming language semantics. If a method in a class is going to return something, it must declare a return type and it must use the return statement to return a value, otherwise nothing will be returned.