PowerShell Return behavior in PowerShell How to work with functions returns


Example

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:

  • Start
  • The newly created registry key (this is because there are some statements that create output that you may not be expecting)
  • Yes, it worked!

Test-Function -ExceptionalReturn Will return:

  • Start
  • Damn, it didn't work!

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:

  • Yes, it worked!

Test-Function -ExceptionalReturn Will return:

  • Damn, it didn't work!

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.