We are no longer accepting contributions to Documentation. Please see our post on meta.

PowerShell

Return behavior in PowerShell All Versions

1.0
2.0
3.0
4.0
5.0
5.1

It can be used to Exit the current scope, which can be a function, script, or script block. In PowerShell, the result of each statement is returned as output, even without an explicit Return keyword or to indicate that the end of the scope has been reached.

This draft deletes the entire topic.

Examples

  • 2
    function earlyexit {
        "Hello"
        return
        "World"
    }
    

    "Hello" will be placed in the output pipeline, "World" will not

  • 1
    get-childitem | foreach-object { if ($_.IsReadOnly) { return } } 
    

    Pipeline cmdlets (ex: ForEach-Object, Where-Object, etc) operate on closures. The return here will only move to the next item on the pipeline, not exit processing. You can use break instead of return if you want to exit processing.

    get-childitem | foreach-object { if ($_.IsReadOnly) { break } } 
    
  • 1

    (paraphrased from about_return)

    The following methods will have the same values on the pipeline

    function foo {
        $a = "Hello"
        return $a
    }
    
    function bar {
        $a = "Hello"
        $a
        return
    } 
    
    function quux {
        $a = "Hello"
        $a
    } 
    
  • Improvements requested:

    • This was posted as an example, but it does not attempt to illustrate the topic. It should possibly be an edit to the topic, a separate topic, or deleted altogether. –  Ranadip Dutta Mar 11 at 17:05
      This example doesn't show anything with respect to function. It more indicates about suppressing output which is very much generic to PS. Incorporating the same in PS Function does not change the effectiveness for the same.
      1. I am not sure what is the problem? I think it is related to topic - Return behvior - without these fixes, user will face incorrect return value from the function.
      2. I think this is related, it shows how return behavior works!
      3. This is definitely related. Add() methods in .NET are notorious for fouling up PowerShell functions, and it's precisely because of PowerShell's technique for determining function output.
      4. I would argue that it's not related, as it's not (to half-borrow a phrase) PowerShell-esque. Why use .NET methods in PowerShell if unrequired? Better served in these cases by something like $MyVariable += "a", which handily has no rogue output.

    We are no longer accepting contributions to Documentation. Improvement requests can no longer be handled.

    0

    Inspired by

    function bar {
     [System.Collections.ArrayList]$MyVariable = @()
     $MyVariable.Add("a") | Out-Null
     $MyVariable.Add("b") | Out-Null
     $MyVariable
    }
    

    The Out-Null is necessary because the .NET ArrayList.Add method returns the number of items in the collection after adding. If omitted, the pipeline would have contained 1, 2, "a", "b"

    There are multiple ways to omit unwanted output:

    function bar
    {
        # New-Item cmdlet returns information about newly created file/folder
        New-Item "test1.txt" | out-null
        New-Item "test2.txt" > $null
        [void](New-Item "test3.txt")
        $tmp = New-Item "test4.txt"
    }
    

    Note: to learn more about why to prefer > $null, see [topic not yet created].

  • 0

    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.

Please consider making a request to improve this example.

Syntax

Syntax

Parameters

Parameters

Remarks

You can read more about the return semantics on the about_Return page on TechNet, or by invoking get-help return from a PowerShell prompt.


Notable Q&A question(s) with more examples/explanation:


about_return on MSDN explains it succinctly:

The Return keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached.

Users who are familiar with languages like C or C# might want to use the Return keyword to make the logic of leaving a scope explicit.

In Windows PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword. Languages like C or C# return only the value or values that are specified by the Return keyword.

Still have a question about Return behavior in PowerShell? Ask Question

Topic Outline


    We are no longer accepting contributions to Documentation. Drafts cannot be modified.