1

If a powershell function is wrapping a python function, so long as no param block is specified, its possible to easily pass all arbitrary args through with $args:

Function scl-hython {
    & "$pythonDir\python.exe" myscript.py --some-arg hython $args
}

However as soon as I specify a param block (with multiple optional non positional paramaters), extra arbitrary args are no longer allowed and you will get an error like this:

A positional parameter cannot be found that accepts argument

Is there a way to enable arbitrary args and explicit ones for the sake of autocompletion?

I should also clarify, I am using multiple non positional parameters that are optional, and this case doesn't seem to be covered in existing similar answers.

3
  • Note that it isn't the use of a param(...) block per se that precludes of of $args, it is the transition from a simple to an advanced function, which happens in one or both of the following cases: a [CmdletBinding()] attribute is used (which only takes effect above a param(...) block) and/or a [Parameter()] attribute is used (which you may also use with the C-style syntax for declaring parameters, though using param(...) consistently is generally preferable). Commented Nov 5, 2022 at 3:16
  • In other words: if you use param(...), you'll still be able to use $args - to refer to all remaining arguments - as long as you neither use the [CmdletBinding()] nor a per-parameter [Parameter()] attribute. Commented Nov 5, 2022 at 3:20
  • Can you add a minimal reproduction of your python script so we can test? Commented Nov 5, 2022 at 4:15

1 Answer 1

1

To get around this issue you can use the metadata attribute of ValueFromRemainingArguments.

Function scl-hython {
    Param(
        [parameter(ValueFromRemainingArguments)]
        $Arguments
    )
    & "$pythonDir\python.exe" myscript.py --some-arg hython $Arguments
}

Alternatively, you can just use the automatic variable $PSBoundParameters with a reference to its values.

Sign up to request clarification or add additional context in comments.

2 Comments

doesn't the parameter method need to be bound to some parameter name?
@SantiagoSquarzon, see edit. Pasted without looking. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.