【发布时间】:2018-03-06 16:29:41
【问题描述】:
我正在尝试创建一个接受管道位置绑定参数和位置绑定参数的日志记录函数。但是,我使用以下代码不断收到此错误:
Function Test
{
[CmdletBinding(SupportsShouldProcess,DefaultParameterSetName='def')]
Param(
[Parameter(Position=0,ParameterSetName='def')]
[String]$Pos1,
[Parameter(ValueFromPipeline,Position=1,ParameterSetName='pip')]
[String]$InputObject,
[Parameter(Position=1,ParameterSetName='def')]
[Parameter(Position=0,ParameterSetName='pip')]
[String]$State
)
Process
{
Switch ($PScmdlet.ParameterSetName)
{
'def' {Write-Host "${State}: $Pos1"}
'pip' {Write-Host "${State}: $InputObject"}
}
}
}
PS C:\> 'this' | Test 'error'
test : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At line:1 char:10
+ 'test' | test 'error'
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (test:String) [Test], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,Test
我可以让函数的位置绑定管道调用与以下示例一起使用:
Function Test
{
Param(
[Parameter(Position=1,ValueFromPipeline)]
[String]$Msg,
[Parameter(Position=0)]
[String]$State
)
Process
{
Write-Host "${State}: $Msg"
}
}
PS C:\> 'this' | Test 'error'
error: this
所以我的问题是:如何创建一个函数,该函数将在命令行 (Test 'message' 'status') 和管道 ('message' | Test 'status') 中获取位置绑定的参数,而无需显式调用参数名称 ('message' | Test -State 'status' )?
【问题讨论】:
-
从管道中移除 ParameterSetName,移除 ParameterSetName='pip'
-
@ArcSet 这样做会导致位置 0 参数被绑定两次,同时绑定到
$InputObject和$State,但它确实停止向我抛出错误。
标签: powershell pipeline powershell-5.0