0

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?

Community
  • 1
  • 1
IttayD
  • 28,271
  • 28
  • 124
  • 178

1 Answers1

3

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
Vesper
  • 18,599
  • 6
  • 39
  • 61
  • This doesn't work with `example -v` or `example -args -v` – IttayD Jul 21 '15 at 04:03
  • `-v` is verbose flag, it is matched by `[cmdletbinding()]` and sets local `$verbosepreference` variable to true, or if written `-v:$false`, to false. You can make it display by quoting, `example "-v"`. – Vesper Jul 21 '15 at 05:03
  • Just tried `example -vvv` and got the `-vvv` in result. Anyway, what do you actually want? – Vesper Jul 21 '15 at 13:19