IttayD
IttayD

Reputation: 29133

Using CmdletBinding without formal parameters

Following a comment to another question, I tried adding CmdletBinding to a function. Here is a toy example

function example {
  [CmdletBinding()]Param()
  $args
}

But trying to use it I get:

> example foo
example : A positional parameter cannot be found that accepts argument 'foo'.
At line:1 char:1
+ example foo
+ ~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [example], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,example

What should I fix so that the function will work with any argument(s) passed to it?

Upvotes: 0

Views: 1357

Answers (1)

Vesper
Vesper

Reputation: 18747

You need to declare a parameter to accept that "foo" within the Param() block. Here's the manual on advanced parameters. In your case, you want the parameter to accept any value that's not matched to any other parameters (none), so you declare it using ValueFromRemainingArguments argument set to true.

function example {
    [CmdletBinding()]
    Param(
        [parameter(ValueFromRemainingArguments=$true)][String[]] $args
    )
    $args
}

An example on how to use:

PS K:\> example foo bar hum
foo
bar
hum

Upvotes: 3

Related Questions