Search code examples
powershellpowershell-5.0

PowerShell - Return doesn't behave as expected


I'm using PowerShell v5.1. I have a question about "Return". Shouldn't "Return" stop script execution?

Get-CimInstance Win32_OperatingSystem | ForEach-Object {
    "Exiting"
    Return
}
"It doesn't"

ForEach ($number in 1..2){
    "Exiting"
    Return
}
"It doesn't"

Result is: Exiting => It doesn't => Exiting

As you can see "Return" behaves differently inside "ForEach-Object" loop then inside "ForEach" loop. What am I missing? Thank you :-)


Solution

  • Per the manual, https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_return?view=powershell-5.1

    Emphasis added:

    Exits the current scope, which can be a function, script, or script block.

    Any time you hit the Return keyword it'll exit the brackets currently be worked within.