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?

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't work with example -v or example -args -v
-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".
Just tried example -vvv and got the -vvv in result. Anyway, what do you actually want?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.