I
I
IkaR492019-07-31 10:55:07
PowerShell
IkaR49, 2019-07-31 10:55:07

How can I specify one required argument and an unlimited number of optional ones in a function?

There is a function

Function foo($a) {
    echo $a 
    echo $args 
}

Naturally, there is no echo, but the main thing is that $a is processed separately, other arguments are processed separately, and their number is not limited and they may not be, but $a must be required. However, in the example above, calling the function with no arguments also works.
If you try to do this:
Function foo {
    param(
        [Parameter (Mandatory = $true, Position = 0)] $a 
    )
    echo $a 
    echo $args
}

Here, on the contrary, calling a function without arguments is impossible, as it should be, but it is impossible to specify more than one argument, because the interpreter complains about the lack of suitable positional parameters.
How to specify both mandatory one parameter and optional and unboundedness of others?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
azarij, 2019-07-31
@IkaR49

and so?

Function foo {
    param(
        [Parameter (Mandatory = $true, Position = 0)] $a,
        [Parameter (ValueFromRemainingArguments)] $other_params

    )
    
    "a:"
    $a
    "other params:"
    $other_params
    
}

foo "param1" "param2" "param3" "param4" "param5" "param6"

the first parameter is in $a, ALL the others are in $other_params.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question