【发布时间】:2016-05-12 09:01:03
【问题描述】:
这是我的代码的 sn-p(基于 this previous question):
$rgdNames = (Get-AzureRmResourceGroupDeployment -ResourceGroupName "$azureResGrpName").DeploymentName
$siblings = $rgdNames | Where-Object{$_ -match "^($hostname)(\d+)$" }
if ($siblings) {
# Make a list of all numbers in the list of hostnames
$serials = @()
foreach ($sibling in $siblings) {
# $sibling -split ($sibling -split '\d+$') < split all digits from end, then strip off everything at the front
# Then convert it to a number and add that to $serials
$hostnumber = [convert]::ToInt32([string]$($sibling -split ($sibling -split '\d+$'))[1], 10)
$serials += $hostnumber
}
(1..$siblingsMax) | foreach { # Iterate over all valid serial numbers
if (!$serials.Contains($_)) { # Stop when we find a serial number that isn't in the list of existing hosts
$serial = $_
# break # FIXME: For some reason, this break statement breaks "too far"
}
}
} else {
$serial = 1
}
write-output("serial = $serial") # does not print
# ...more statements here, but they're never called :(
我已经研究了一段时间,但不明白为什么break 语句(如果未注释)会停止我的程序,而不是仅仅跳出它的foreach 循环。 foreach 有什么我不知道的地方,还是 break 的工作方式与在 Java 中不同?
目前,我正在使用额外的if 测试来解决这个问题,这并不意味着(太多)循环运行其整个长度。但是很丑!
【问题讨论】:
-
呃,不,我没有,但是在将代码粘贴到这篇文章后,我犯了格式错误。抱歉,感谢您接听。
标签: loops powershell break