4

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If used directly (i.e. not in a script), that version may actually exit your whole command prompt. Just saying.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.