2

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

1 Answer 1

2

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:

  • for the optional parameters when reading from the pipeline, or
  • for the mandatory parameter when not reading from the pipeline.
Sign up to request clarification or add additional context in comments.

1 Comment

Seems like best option is to keep the way it is, mandatory param appears more often - which is why it would be even more pointless to make it named

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.