How to exit from ForEach-Object in PowerShell

前端 未结 9 1807
北海茫月
北海茫月 2020-11-27 20:30

I have the following code:

$project.PropertyGroup | Foreach-Object {
    if($_.GetAttribute(\'Condition\').Trim() -eq $propertyGroupConditionName.Trim()) {
           


        
9条回答
  •  一向
    一向 (楼主)
    2020-11-27 21:06

    There are differences between foreach and foreach-object.

    A very good description you can find here: MS-ScriptingGuy

    For testing in PS, here you have scripts to show the difference.

    ForEach-Object:

    # Omit 5.
    1..10 | ForEach-Object {
    if ($_ -eq 5) {return}
    # if ($_ -ge 5) {return} # Omit from 5.
    Write-Host $_
    }
    write-host "after1"
    
    # Cancels whole script at 15, "after2" not printed.
    11..20 | ForEach-Object {
    if ($_ -eq 15) {continue}
    Write-Host $_
    }
    write-host "after2"
    
    # Cancels whole script at 25, "after3" not printed.
    21..30 | ForEach-Object {
    if ($_ -eq 25) {break}
    Write-Host $_
    }
    write-host "after3"
    

    foreach

    # Ends foreach at 5.
    foreach ($number1 in (1..10)) {
    if ($number1 -eq 5) {break}
    Write-Host "$number1"
    }
    write-host "after1"
    
    # Omit 15. 
    foreach ($number2 in (11..20)) {
    if ($number2 -eq 15) {continue}
    Write-Host "$number2"
    }
    write-host "after2"
    
    # Cancels whole script at 25, "after3" not printed.
    foreach ($number3 in (21..30)) {
    if ($number3 -eq 25) {return}
    Write-Host "$number3"
    }
    write-host "after3"
    

提交回复
热议问题