Jens
Jens

Reputation: 11

Array parameter in a powershell function does not load the first element

I have a function that takes one string parameter, and one array of string parameter

Function w
{
    param([string]$format, [string[]]$args)
    Write-Host $format
    Write-Host $args
}

Then I execute the function in the following way:

w "formatParam" "args1" "args2"
w "formatParam" "args1" "args2" "args3"
w "formatParam" "args1" "args2" "args3" "args4"
w "formatParam" "args1" "args2" "args3" "args4" "args5"

As can be seen in the output, the string array does not seem to load the first parameter, that is meant to go into the array:

formatParam
args2
formatParam
args2 args3
formatParam
args2 args3 args4
formatParam
args2 args3 args4 args5

Any ideas?

Upvotes: 1

Views: 308

Answers (2)

Benjamin Hubbard
Benjamin Hubbard

Reputation: 2917

It's the name of your parameter, "args". $Args is an automatic variable, so shouldn't be used outside its purpose. From Get-Help about_Automatic_Variables:

Contains an array of the undeclared parameters and/or parameter values that are passed to a function, script, or script block. When you create a function, you can declare the parameters by using the param keyword or by adding a comma-separated list of parameters in parentheses after the function name.

If you change the name of your parameter, and then add commas between the arguments of your second parameter so that it is an actual array, it will work.

Upvotes: 1

briantist
briantist

Reputation: 47832

$args is Special

$args is already a special variable in powershell; you shouldn't be declaring it as a parameter because you're overriding it. Let's name it something else, like $remaining.

Arrays use commas

The way you're passing the arguments in (with spaces) makes them look like different parameters. To pass an array you'd have to call it like this:

w "formatParam" "args1" "args2","args3","args4","args5"

with commas. Since that's likely not what you want, you need to rewrite the function.

Remaining arguments

Function w
{
    param(
        [string]$format, 
        [Parameter(
            ValueFromRemainingArguments=$true
        )            
        [string[]]
        $remaining
    )
    Write-Host $format
    Write-Host $remaining
}

And now you should be able to call it like so:

w "formatParam" "args1" "args2" "args3" "args4" "args5"

Upvotes: 2

Related Questions