32

I have a function that looks something like this:

function global:Test-Multi {
    Param([string]$Suite)
    & perl -S "$Suite\runall.pl" -procs:$env:NUMBER_OF_PROCESSORS
}

I would like to allow the user to specify more parameters to Test-Multi and pass them directly to the underlying legacy perl script.

Does powershell provide a mechanism to allow additional variadic behavior for this purpose?

3 Answers 3

32

After seeing your comment, option 3 sounds like exactly what you want.


You have a few options:

  1. Use $args (credit to hjpotter92's answer)

  2. Explicitly define your additional parameters, then parse them all in your function to add them to your perl call.

  3. Use a single parameter with the ValueFromRemainingArguments argument, e.g.

     function global:Test-Multi {
         Param(
             [string]$Suite,
             [parameter(ValueFromRemainingArguments = $true)]
             [string[]]$Passthrough
             )
         & perl -S "$Suite\runall.pl" -procs:$env:NUMBER_OF_PROCESSORS @Passthrough
     }
    
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think your "ValueFromRemainingArguments" link goes to the right place....
@BillyONeal thank you, updated. It's a long-ish document, so CTRL+F for ValueFromRemainingArguments is recommended.
@BillyONeal nice, I really should have added an example
18

$args is not going to pass through arguments correctly. if you want the arguments to remain as separate arguments, you should use @args instead.

2 Comments

Huge thanks! It was exactly what I needed. Using $ formats your arguments as a single string. @ is the way to go for a proper pass.
This is what I was looking for as well. "$args" might work for arguments, but not for parameters. @args seems like the equivalent to bash's "$@"? But since search engines strip special characters, all of this is next to impossible to find.
6

I'm not sure about what you wish to achieve, but the arguments passed to a function are accessible in the $args variable available inside the function.

4 Comments

But $args would contain '-Suite' and its setting as well. I only want to forward arguments my function is not handling.
@BillyONeal You can filter the $args array and remove -Suite parameter.
sure, I can think of ways to do it, but if PS already had a formal way to declare this I wanted to use that.
To pass the received args to another function, one must use @args and not $args

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.