scobi
scobi

Reputation: 14558

How to disable common parameter parsing in PowerShell functions?

I'd like to disable PowerShell's "common parameters" for one of my functions. I've been working on a set of extensions to p4.exe (the Perforce command line utility) by writing a function something like this:

function p4(
    [parameter(valuefromremainingarguments=1)]
    [string[]]$cmdline)
{
    # ...do some fun stuff with $cmdline...
    p4.exe $cmdline  # for illustration only - actual implementation uses .net objects
}

The point is to be able to use p4 just like I normally do on the command line, except sometimes magically some parameters will get reprocessed (to add new commands or call different tools or whatever) and it will always feel as if I'm just using the normal p4 command line.

This is working pretty well, until I start using a parameter like '-o'.

p4 -p 1666 user -o scobi

In this case, I get an error from PowerShell:

p4 : Parameter cannot be processed because the parameter name 'o' is ambiguous. Possible matches include: -OutVariable -OutBuffer.

The only way I've found around it is to quote my parameters:

p4 -p 1666 user '-o' scobi
p4 '-p 1666 user -o scobi'

Yucky, and gets in the way of my goal of having this function be a transparent superset of p4.exe.

Is there a magic attribute I can attach to my function to make it tell the shell "I don't support common parameters"? Or are there any other ways around this?

Upvotes: 3

Views: 3822

Answers (1)

Roman Kuzmin
Roman Kuzmin

Reputation: 42063

Do not use advanced function at all, use a normal function with no parameters. Inside the function use $args to refer to the arguments.

function p4()
{
    $args
}

p4 -p 1666 user -o scobi

Output:

-p
1666
user
-o
scobi

UPDATE

In fact the function still can use its own parameters, for example:

function p4($myparam)
{
    "param $myparam"
    $args
}

p4 -p 1666 user -o scobi -myparam value

Output:

param value
-p
1666
user
-o
scobi

Caution: parameter names should not conflict with other potential arguments. For example, this does not work:

function p4($param)
{
    "param $param"
    $args
}

p4 -p 1666 user -o scobi -param value

Result:

ERROR: ParameterBindingException:
p4 : Cannot bind parameter because parameter 'param' is specified more than once. ...

Upvotes: 5

Related Questions