powershell 从函数退出循环

arknldoa  于 3个月前  发布在  Shell
关注(0)|答案(2)|浏览(70)

我想从一个函数中打破下面的循环,这个函数的调用方式如下所示。

Function test {
    $i++
    IF ($i -eq 10) {continue}
}

$Computers = "13","12","11","10","9","8","7","6","5","4","3","2","1"
ForEach ($Computer in $Computers) {
    Test
    write-host "Fail"
}

字符串

aiqt4smr

aiqt4smr1#

如果我跟踪你...

Function test {
    $args[0] -eq 10
}

$Computers = "13","12","11","10","9","8","7","6","5","4","3","2","1"
ForEach ($Computer in $Computers) {
    if(Test $Computer) {break} else {$Computer}
}

字符串

ftf50wuq

ftf50wuq2#

我试过了,你真的可以。

Function Test ($i) {
    if ($i -eq 10) {continue}
    if ($i -eq 3)  {break}
}

$numbers = "13","12","11","10","9","8","7","6","5","4","3","2","1"
ForEach ($number in $numbers) {
    Test $number
    write-host "$number"
}

字符串
输出量:

13
12
11
9
8
7
6
5
4


因此,跳过了10,并在3时退出循环。
这样的编码是一种不好的做法,因为通常不期望函数中断循环。
除非函数的名称与循环有关,如“Exit-LoopOnFailure()”

相关问题