【问题标题】:Is there a way pass a Cmdlet with some parameters to another Cmdlet that pipes the remaining parameters to it?有没有办法将带有一些参数的 Cmdlet 传递给另一个将剩余参数通过管道传递给它的 Cmdlet?
【发布时间】:2015-02-16 00:12:07
【问题描述】:

this technique to use Cmdlets as "delegates" 的基础上,我留下了这个问题:

有没有办法将带有指定命名或位置参数的 commandlet 传递给另一个使用 powershell 管道将剩余参数绑定到传递的 commandlet 的 commandlet?

这是我希望能够运行的代码 sn-p:

Function Get-Pow{
    [CmdletBinding()] 
    Param([Parameter(ValueFromPipeline=$true)]$base,$exp)
    PROCESS{[math]::Pow($base,$exp)}
}
Function Get-Result{
    [CmdletBinding()]
    Param([Parameter(ValueFromPipeline=$true)]$x,$Cmdlet)
    $x | . $Cmdlet
}

10 | Get-Result -Cmdlet 'Get-Pow -exp 2'
10 | Get-Result -Cmdlet 'Get-Pow -exp 3'
10 | Get-Result -Cmdlet Get-Pow -exp 2
10 | Get-Result -Cmdlet Get-Pow -exp 3

Get-Result 的前两次调用导致CommandNotFoundException,因为Get-Pow -exp 2“不是cmdlet 的名称。”

Get-Result 的最后两次调用导致NamedParameterNotFound,Get-Result,因为该语法实际上试图将参数-exp 传递给它没有的Get-Result

还有其他方法可以设置它以使其正常工作吗?

【问题讨论】:

  • 您可以为 Get-Results 提供一个可以接受这些参数的可选参数吗?可能是哈希表的形式?
  • @Matt 我没有找到在$x | . $Cmdlet 行上传递参数的方法。但我确实设法让您的“可选参数”方法与Invoke-Expression 一起使用。请参阅下面的答案。
  • 我收回,$x | . $Cmdlet @arguments 也可以工作。

标签: powershell delegates pipeline


【解决方案1】:

我不确定这是不是最好的方法,但至少它类似于 powershell 习惯用法:

Function Get-Amount{
    [CmdletBinding()] 
    Param(
    [Parameter(ValueFromPipeline=$true)]$t,
    [Parameter(position=1)]$r,
    [Parameter(position=2)]$P)
PROCESS{$P*[math]::Pow(1+$r,$t)}
}
Function Get-Result{
    [CmdletBinding()]
    Param(
    [Parameter(ValueFromPipeline=$true)]$x,
    [Parameter(Position=1)]$Cmdlet,        #positional arguments here makes calling more readable
    [Alias('args')]                        #careful, $args is a special variable
    [Parameter(Position=2)]$Arguments=@()) #the default empty array is required for delegate style 1
PROCESS{
    #invoke style 1                        #works with delegate styles 1,2,3
    iex "$x | $Cmdlet @Arguments"          

    #invoke style 2                        #works with delegate styles 2,3
    $x | . $Cmdlet @Arguments              
}}

5,20 | Get-Result 'Get-Amount -r 0.05 -P 100' #delegate style 1
5,20 | Get-Result Get-Amount 0.05,100         #delegate style 2
5,20 | Get-Result Get-Amount @{r=0.05;P=100}  #delegate style 3

结果:

127.62815625
CommandNotFoundException
265.329770514442
CommandNotFoundException
127.62815625
127.62815625
265.329770514442
265.329770514442
127.62815625
127.62815625
265.329770514442
265.329770514442

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多