loops - 如何打破 Powershell 中的 Foreach 循环?

标签 loops powershell foreach break powershell-4.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" 被执行了,而它不应该被执行。

最佳答案

break 语句用于退出循环或 switch block ,这正是它在您的情况下所做的。相反,您可能希望在发现无效参数时使用 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 了解更多信息。

关于loops - 如何打破 Powershell 中的 Foreach 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25911180/

相关文章:

c# - 从 PowerShell 调用时无法在 dll 中转换透明代理,但在 C# 控制台应用程序中成功

php - 如何在 PHP 中使用 ArrayIterator append 带有键的元素?

php - 从 JSON 输入中检索数组键

php - 具有 3 列的 MYsql GROUP_CONCAT 在 PHP 中执行

python - 执行数学 sigma 和的最快、最有效和 pythonic 方法是什么?

c - 有条件地向后或向前迭代的最快方法

.net - Powershell 和 winapi SystemParametersInfo 函数

c - 了解C语言中for循环的基础知识

javascript - 两次调用 javascript 函数的问题

Powershell - 检查 CD 是否在 CD-ROM 驱动器中