Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass-through parameters in a powershell function?

Tags:

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?

like image 240
Billy ONeal Avatar asked Nov 13 '15 21:11

Billy ONeal


People also ask

How do I pass multiple parameters to a PowerShell function?

To pass multiple parameters you must use the command line syntax that includes the names of the parameters. For example, here is a sample PowerShell script that runs the Get-Service function with two parameters. The parameters are the name of the service(s) and the name of the Computer.

How do you call a parameter in PowerShell?

One way to use PowerShell function parameters in a script is via parameter name -- this method is called named parameters. When calling a script or function via named parameters, use the entire name of the parameter. For example, perhaps the example param block above is stored in a PowerShell script called foo. ps1.

How do you pass multiple parameters to a function?

The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don't know how many arguments will be sent to the function.


1 Answers

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
    }
    
like image 182
briantist Avatar answered Oct 15 '22 13:10

briantist