Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit a PowerShell function but continue the script

Tags:

This might seem like a very very stupid question, but I can't really figure it out. I'm trying to have the function stop when it finds its first hit (match) and then continue with the rest of the script.

Code:

Function Get-Foo {
    [CmdLetBinding()]
    Param ()

    1..6 | ForEach-Object {
        Write-Verbose $_
        if ($_ -eq 3) {
            Write-Output 'We found it'

            # break : Stops the execution of the function but doesn't execute the rest of the script
            # exit : Same as break
            # continue : Same as break
            # return : Executes the complete loop and the rest of the script
        }
        elseif ($_ -eq 5) {
            Write-Output 'We found it'
        }
    }
}

Get-Foo -Verbose

Write-Output 'The script continues here'

Desired result:

VERBOSE: 1
VERBOSE: 2
VERBOSE: 3
We found it
The script continues here

I've tried using break, exit, continue and return but none of these get me the desired result. Thank you for your help.

like image 319
DarkLite1 Avatar asked Apr 26 '16 07:04

DarkLite1


People also ask

How do you break out of a function in PowerShell?

Open a PowerShell console session, type exit , and press the Enter key. The PowerShell console will immediately close. This keyword can also exit a script rather than the console session.

Does closing PowerShell stop script?

Using PowerShell Exit keywordExit keyword in PowerShell can terminate the script, console session. If you open the PowerShell console and type exit, it will immediately close. Using the Exit keyword in a script terminates only the script and not the console session from where we run the script.

How do you exit a loop in PowerShell?

Using break in loopsWhen a break statement appears in a loop, such as a foreach , for , do , or while loop, PowerShell immediately exits the loop. A break statement can include a label that lets you exit embedded loops. A label can specify any loop keyword, such as foreach , for , or while , in a script.


1 Answers

As was mentioned, Foreach-object is a function of its own. Use regular foreach

Function Get-Foo {
[CmdLetBinding()]
Param ()

$a = 1..6 
foreach($b in $a)
{
    Write-Verbose $b
    if ($b -eq 3) {
        Write-Output 'We found it'
        break
    }
    elseif ($b -eq 5) {
        Write-Output 'We found it'
    }
  }
}

Get-Foo -Verbose

Write-Output 'The script continues here'
like image 169
Andrey Marchuk Avatar answered Sep 23 '22 13:09

Andrey Marchuk