toofat
toofat

Reputation:

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 :-)

Upvotes: 0

Views: 252

Answers (1)

Tim Brigham
Tim Brigham

Reputation: 574

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.

Upvotes: 1

Related Questions