功能流水线如何跳过流程块?类似于继续在foreach循环中

时间:2019-05-17 14:01:53

标签: powershell

我正在使用一个函数来接受多个对象的管道输入。

如果属性符合某些条件,我希望能够跳过对象的处理;类似于在foreach循环中使用“ Continue”。我意识到我可以使用switch / If语句,但是我试图找到是否有一种方法可以完全跳过该对象。 下面的简单代码或多或少显示了我要完成的工作

Function Get-Foobar{
 Param (
    [parameter(ValueFromPipelineByPropertyName)][string]$Item
 )

    Begin{ 
    # DO SOME INIT STUFF
    }

    Process{
        If($Item -ne "Foobar") { 
        #SOMEHOW SKIP THE PROCESS BLOCK#
        # CONTINUE? BREAK? RETURN? WHAT?
        } 
        Else{
            Write-host "Item was $($Item)"
        }

        #Continue doing stuff here.
        Write-host "Evertying was totally $Item"

    }
    End {
    # DO CLEAN UP STUFF
     }
}

$test = @([pscustomobject]@{Item = "Foobar"},[pscustomobject]@{Item = "NotFubar"} )


$test |Get-Foobar

Item was Foobar
Evertying was totally Foobar
Evertying was totally NotFubar <---- liked to skip this without having it in the upper if/Else

1 个答案:

答案 0 :(得分:0)

Process块是一个独立的脚本块,因此continue不会对其造成影响。

return中使用process跳到管道中的下一个输入项:

function Get-Foobar {
    param(
        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [string]$Item
    )

    Begin { 
        # DO SOME INIT STUFF
    }

    Process {
        if ($Item -ne "Foobar") { 
            # skip it!
            return
        }
        else {
            Write-host "Item was $($Item)"
        }

        #Continue doing stuff here.
        Write-host "Evertying was totally $Item"

    }
    End {
        # DO CLEAN UP STUFF
    }
}