Powershell pipe and command line arguments
I have a Powershell function that takes 3 arguments (two of them optional), parameters for function are defined like this:
Param(
[parameter(Mandatory=$true, ValueFromPipeline=$true)]
[String]
$text,
[parameter(Mandatory=$false)]
[String]
$from = "auto",
[parameter(Mandatory=$false)]
[String]
$to = "lt"
)
If I run the script with 1, 2 or 3 command line parameters - everything works fine. If I run with no parameters, but pass value from pipeline - everything works fine. Working examples:
Foo "hello"
Foo "hola" es
Foo "hola" es lt
"hello" | Foo
I want to be able to pass value from pipeline to the first argument and provide additional command line parameters, but I recieve error: "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".
There is one working example, if i provide parameters by name:
"hello" | Foo -from en -to ru
But I don't really like typing the name of parameter all the time. Can this be ommited, is there any shortcut? Not working (wishlist) examples (any will do):
"hello" | Foo en es
"hello" | Foo - en es
"hello" | Foo -- en es
You could make -Text
the last positional parameter:
Param(
[Parameter(Position=2, Mandatory=$true, ValueFromPipeline=$true)]
[String]$text,
[Parameter(Position=0, Mandatory=$false)]
[String]$from = "auto",
[Parameter(Position=1, Mandatory=$false)]
[String]$to = "lt"
)
but then you'll have to call the function with named parameters when not reading the manadatory parameter from a pipeline or calling the function with 3 arguments:
Foo -Text 'something'
otherwise you'll be prompted for input:
PS C:> Foo 'something'
cmdlet Foo at command pipeline position 1
Supply values for the following parameters: _
So, basically you can choose in which scenario you want to provide parameter names:
上一篇: Powershell获取
下一篇: Powershell管道和命令行参数