我正在寻找一种方法来打破我的Foreach循环。
这是我的代码
$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"
我不明白为什么它没有破坏我的代码,因为这是我执行时的结果:
Your parameter doesn't match
Please use one of this parameter desktopstudio controller storefront desktopdirector licenseserver
I'm here
您可以看到我的Write-Host "I'm here"
被执行但不应该执行。
答案 0 :(得分:3)
break语句用于退出循环或切换块,这就是你的情况。相反,您可能希望在找到无效参数时使用exit命令停止执行脚本。
$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"
有关详细信息,另请参阅Get-Help about_Break
,Get-Help exit
,Get-Help return
。