问题
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:
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.
来源:https://stackoverflow.com/questions/25911180/how-to-break-foreach-loop-in-powershell