How do I pass multiple parameters into a function in PowerShell?

If I have a function which accepts more than one string parameter, the first parameter seems to get all the data assigned to it, and remaining parameters are passed in as empty.

A quick test script:

Function Test([string]$arg1, [string]$arg2)
{
    Write-Host "`$arg1 value: $arg1"
    Write-Host "`$arg2 value: $arg2"
}

Test("ABC", "DEF")

The output generated is

$arg1 value: ABC DEF
$arg2 value: 

The correct output should be:

$arg1 value: ABC
$arg2 value: DEF

This seems to be consistent between v1 and v2 on multiple machines, so obviously, I’m doing something wrong. Can anyone point out exactly what?

15 s
15

Parameters in calls to functions in PowerShell (all versions) are space-separated, not comma separated. Also, the parentheses are entirely unneccessary and will cause a parse error in PowerShell 2.0 (or later) if Set-StrictMode -Version 2 or higher is active. Parenthesised arguments are used in .NET methods only.

function foo($a, $b, $c) {
   "a: $a; b: $b; c: $c"
}

ps> foo 1 2 3
a: 1; b: 2; c: 3

Leave a Comment