Controlling Return Values

by May 5, 2016

In the previous tip we explained why functions can have multiple return values, and that anything you leave behind will be added to the return values.

If you'd like PowerShell to behave like a classic scripting language, and exclusively set the return value with the "return" keyword, then here is a simple yet clever trick: encapsulate the code in a script block, and assign its value to $null. This ensures that all previously emitted values are discarded, and only the value defined by "return" will become the return value:

function Do-Something
{
    param($Text)

    # call the inner logic inside a script block
    $null = . {
        # whatever is emitted from here goes to $null
        Get-Date
        $sapi = New-Object -ComObject sapi.spvoice
        $sapi.Speak($Text)
        $Text = 12
        "Text = $Text"
    }
    
    return 'this IS THE ONLY return value now!'
}

Do-Something -Text "Hello"

Twitter This Tip! ReTweet this Tip!