Sunday, March 22, 2009

Return from functions in PowerShell

I wrote 2 blog posts about returning values from functions (here and here) in past, however as I just noticed I haven’t posted any solutions there.

There are in fact at least 3 solutions to this problem.

1.) First was already mentioned – don’t use function as function, however as subroutine and assign value back to variable provided by argument.

2.) Second approach is that you can always consider function to return array and only take last element:

$MyVar = [array]$(Function) | Select –Last 1

That will cast output from function to array (even if it has only single member) and then return last element of that array.

3.) Another solution provided by Oisin is to redirect whole script block to null:

“If you have no clue about/control over whether things may or may not emit and/or are just a bit lazy, dot source a script block redirected to $null. Dot sourcing it ensures it is evaluated in root function scope, and also throws all output away.”

function Test {

    . {
        1, 2, 3
    } > $null

    return 4,5,6
}

I like Oisin’s approach most – it is not hard to implement and works really nicely.

 

One warning though – you shouldn’t take this as general solution and it is not recommended. This approach is mostly useful in case you execute some functions from external source (like invoke from XML file) or you have very complex functions with tons of unexpected returns (especially handling with XML files).

No comments: