How to work with functions returns

suggest change

A function returns everything that is not captured by something else.

If you use return, statements after that line do not run.

Like this:

Function Test-Function
{
    Param
    (
        [switch]$ExceptionalReturn
    )
    "Start"
    if($ExceptionalReturn){Return "Damn, it didn't work!"}
    New-ItemProperty -Path "HKCU:\" -Name "test" -Value "TestValue" -Type "String"
    Return "Yes, it worked!"
}

Test-Function

Will return:

Test-Function -ExceptionalReturn Will return:

If you do it like this:

Function Test-Function
{
    Param
    (
        [switch]$ExceptionalReturn
    )
    . {
       "Start"
        if($ExceptionalReturn)
        {
            $Return = "Damn, it didn't work!"
            Return
        }
        New-ItemProperty -Path "HKCU:\" -Name "test" -Value "TestValue" -Type "String"
        $Return = "Yes, it worked!"
        Return 
    } | Out-Null
    Return $Return
}

Test-Function

Will return:

Test-Function -ExceptionalReturn Will return:

With this trick you can control what the function returns even when you are not sure what each statement will output.

It works like this:

.{ <Statements> } | Out-Null

The . dot-sources the script block into the current scope. The braces mark the script block. Out-Null discards its output. Because the block is dot-sourced, variables created inside it are visible to the rest of the function. return inside that block still leaves the function; this sample uses return with no value after storing the message, so execution continues at Return $Return.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents