【问题标题】:How to pass custom filter function to Where-Object如何将自定义过滤器功能传递给 Where-Object
【发布时间】:2013-03-20 23:18:22
【问题描述】:

在过去的几个小时里,我试图弄清楚如何将脚本块传递给一个函数,以用作 where 对象的过滤器。我还没有找到任何文档,我一定是遗漏了一些东西。我在What is the recommended coding style for PowerShell? 中看到了“过滤器脚本:”和“功能:脚本”定义,但我不知道它们是如何使用的,我在任何地方都找不到。

function Test
{
    Param(
            $f,     
            $What
    )

    $x = $What | where $f
    $x
}

$mywhat = @('aaa', 'b', 'abb', 'bac') 
filter script:myfilter {$_ -like 'a*'}
Test -What $mywhat -xx $myfilter

有人可以指点我正确的方向吗?

【问题讨论】:

    标签: powershell powershell-2.0


    【解决方案1】:

    不清楚你在这里要求什么。

    过滤器是一个函数,而不是一个脚本块。 where-object 将脚本块作为输入。如果要使用参数指定函数内部的 where 条件,可以使用 scriptblock-parameter。

    function Test
    {
        Param(
                [scriptblock]$f,     
                $What
        )
    
        $x = $What | where $f
        $x
    }
    
    $myfilter = {$_ -like 'a*'}
    Test -What $mywhat -f $myfilter
    
    #or combine them
    Test -What $mywhat -f {$_ -like 'a*'}
    

    如果您只是想使用过滤器,那么可以这样做:

    filter script:myfilter { if($_ -like 'a*') { $_ }}
    
    $mywhat | myfilter
    

    这将等于$mywhat | where {$_ -like 'a*'}

    【讨论】:

    • 感谢格雷默!这就是我一直在寻找的东西,我相信我一开始就尝试过 - 还是有问题。
    猜你喜欢
    • 2014-01-23
    • 2013-06-03
    • 2022-06-24
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    相关资源
    最近更新 更多