How to work with functions returns
suggest changeA 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:
- 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 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.