如何在Powershell中打破Foreach循环? [英] How to break Foreach loop in Powershell?

查看:730
本文介绍了如何在Powershell中打破Foreach循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找打破Foreach循环的方法.

I'm looking for a way to break my Foreach loop.

这是我的代码

$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

您可以看到我的Write-Host "I'm here"被执行了,而它却没有执行.

You can see that my Write-Host "I'm here" is executed while it should not.

推荐答案

break语句用于退出循环或switch块,这正是您的情况.相反,您可能想在发现无效参数时使用exit命令停止执行脚本.

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"

有关更多信息,另请参见Get-Help about_BreakGet-Help exitGet-Help return.

See also Get-Help about_Break, Get-Help exit, Get-Help return for more information.

这篇关于如何在Powershell中打破Foreach循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆