有没有办法创建一个Cmdlet“委托”支持管道参数绑定? [英] Is there a way to create a Cmdlet "delegate" that supports pipeline parameter binding?
问题描述
在.NET中,如果您的实例可能从一个调用更改为另一个调用的子例程,则可以将委托传递给使用子例程的方法。 您也可以在Powershell中进行此操作。您还可以使用已被描述为Powershell相当于匿名功能的脚本块。惯用的powerhell使用了powershell的管道参数绑定。但是,代理和脚本块似乎都没有使用Powershell的管道参数绑定。
In .NET if you have a subroutine whose implementation might change from one call to another, you can pass a delegate to the method that uses the subroutine. You can also do this in Powershell. You can also use scriptblocks which have been described as Powershell's equivalent of anonymous functions. Idiomatic powershell, however, makes use of powershell's pipeline parameter bindings. But neither delegates nor scriptblocks seem to make use of Powershell's pipeline parameter bindings.
有没有一种(惯用的)方式将powershell命令行路径传递给另一个命令行,以保留对管道参数绑定的支持?
Is there a (idiomatic) way to pass a powershell commandlet to another commandlet in a way that preserves support for pipeline parameter bindings?
这是一个我想要做的代码片段:
Here is a code snippet of what I'd like to be able to do:
Function Get-Square{
[CmdletBinding()]
Param([Parameter(ValueFromPipeline=$true)]$x)
PROCESS{$x*$x}
}
Function Get-Cube{
[CmdletBinding()]
Param([Parameter(ValueFromPipeline=$true)]$x)
PROCESS{$x*$x*$x}
}
Function Get-Result{
[CmdletBinding()]
Param([Parameter(ValueFromPipeline=$true)]$x,$Cmdlet)
PROCESS{$x | $Cmdlet}
}
10 | Get-Result -Cmdlet {Get-Square}
10 | Get-Result -Cmdlet {Get-Cube}
推荐答案
我会工作您的函数定义已经有一些语法问题,以及如何传递参数:
That'll work. You've just got some syntax issues with your function definitions and how you're passing the parameters:
Function Get-Square{
[CmdletBinding()]
Param([Parameter(ValueFromPipeline=$true)]$x)
$x*$x
}
Function Get-Cube{
[CmdletBinding()]
Param([Parameter(ValueFromPipeline=$true)]$x)
$x*$x*$x
}
Function Get-Result{
[CmdletBinding()]
Param([Parameter(ValueFromPipeline=$true)]$x,$Cmdlet)
$x | . $cmdlet
}
10 | Get-Result -Cmdlet Get-Square
10 | Get-Result -Cmdlet Get-Cube
100
1000
这篇关于有没有办法创建一个Cmdlet“委托”支持管道参数绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!