Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 923
Adeel ASIF Avatar asked Oct 26 '25 16:10

Adeel ASIF


1 Answers

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.