How to work with functions returns

suggest change

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

If u use the return keyword, every statement after the return line will not be executed!

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 the returned output even if you are not sure what will each statement will spit out.

It works like this

.{<Statements>} | Out-Null

the . makes the following scriptblock included in the code

the {} marks the script block

the | Out-Null pipes any unexpected output to Out-Null (so it is gone!)

Because the scriptblock is included it gets the same scope as the rest of the function.

So you can access variables who were made inside the scriptblock.

Feedback about page:

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



Table Of Contents