如何在Powershell中打破Foreach循环?

时间:2014-09-18 11:14:27

标签: loops powershell foreach break powershell-v4.0

我正在寻找一种方法来打破我的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"被执行但不应该执行。

1 个答案:

答案 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_BreakGet-Help exitGet-Help return