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.

openCivilisation
  • 796
  • 1
  • 8
  • 25
  • 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](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Functions_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). – mklement0 Nov 05 '22 at 03: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_. – mklement0 Nov 05 '22 at 03:20
  • Can you add a minimal reproduction of your python script so we can test? – Santiago Squarzon Nov 05 '22 at 04:15

1 Answers1

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.