I have the following code:
$project.PropertyGroup | Foreach-Object {
if($_.GetAttribute(\'Condition\').Trim() -eq $propertyGroupConditionName.Trim()) {
Since ForEach-Object
is a cmdlet, break
and continue
will behave differently here than with the foreach
keyword. Both will stop the loop but will also terminate the entire script:
break:
0..3 | foreach {
if ($_ -eq 2) { break }
$_
}
echo "Never printed"
# OUTPUT:
# 0
# 1
continue:
0..3 | foreach {
if ($_ -eq 2) { continue }
$_
}
echo "Never printed"
# OUTPUT:
# 0
# 1
So far, I have not found a "good" way to break a foreach script block without breaking the script, except "abusing" exceptions:
throw:
try {
0..3 | foreach {
if ($_ -eq 2) { throw }
$_
}
} catch { }
echo "End"
# OUTPUT:
# 0
# 1
# End
The alternative (which is not always possible) would be to use the foreach
keyword:
foreach:
foreach ($_ in (0..3)) {
if ($_ -eq 2) { break }
$_
}
echo "End"
# OUTPUT:
# 0
# 1
# End