2013-03-20 64 views
0

对于最后几小时,我试图弄清楚如何将scriptblock传递给函数以用作哪里对象的过滤器。我还没有找到任何文件,我一定错过了一些东西。我在What is the recommended coding style for PowerShell?中看到了“过滤脚本:”和“函数:脚本”的定义,但我不知道如何使用它们,我无法在任何地方找到它。如何将自定义过滤器函数传递给Where对象

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 

有人能请我指出正确的方向吗?

回答

2

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

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

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*'}

+0

感谢Graimer!这就是我一直在寻找的东西,我相信我在一开始就尝试过这种方式 - 必须仍然有错误。 – JankoHrasko 2013-03-21 00:24:59

相关问题