Adeel ASIF
Adeel ASIF

Reputation: 3524

How to break Foreach loop in Powershell?

I'm looking for a way to break my Foreach loop.

This is my code

$MyArray = @("desktopstudio","controller","storefront","desktopdirector","licenseserver")

$component = "toto,blabla"

$component = $component.Split(",")

foreach ($value in $component)
{

    if ($MyArray -notcontains $value)
    {
        Write-host "Your parameter doesn't match"
        Write-host "Please use one of this parameter $MyArray"
        Break
    }

}

write-host "I'm here"

I don't understand why it's not breaking my code, because this is the result when I execute it :

Your parameter doesn't match
Please use one of this parameter desktopstudio controller storefront desktopdirector licenseserver
I'm here

You can see that my Write-Host "I'm here" is executed while it should not.

Upvotes: 4

Views: 23538

Answers (1)

user121489
user121489

Reputation:

The break statement is used to exit from a loop or switch block which is what it is doing in your case. Instead, you probably want to use the exit command to stop execution of your script when an invalid parameter is found.

$MyArray = @("desktopstudio","controller","storefront","desktopdirector","licenseserver")

$component = "toto,blabla"

$component = $component.Split(",")

foreach ($value in $component)
{

    if ($MyArray -notcontains $value)
    {
        Write-host "Your parameter doesn't match"
        Write-host "Please use one of this parameter $MyArray"
        exit   # <--- change is here
    }

}

write-host "I'm here"

See also Get-Help about_Break, Get-Help exit, Get-Help return for more information.

Upvotes: 3

Related Questions