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?
The correct answer has already been provided but this issue seems prevalent enough to warrant some additional details for those wanting to understand the subtleties. I would have added this just as a comment but I wanted to include an illustration--I tore this off my quick reference chart on PowerShell functions. This assumes function f's signature is
f($a, $b, $c)
:Thus, one can call a function with space-separated positional parameters or order-independent named parameters. The other pitfalls reveal that you need to be cognizant of commas, parentheses, and white space.
For further reading see my article Down the Rabbit Hole: A Study in PowerShell Pipelines, Functions, and Parameters just published on Simple-Talk.com. The article contains a link to the quick reference/wall chart as well.
If you try:
you get:
so you see that the parenthesis separates the parameters
If you try:
you get:
Now you could find some immediate usefulness of the parenthesis - a space will not become a separator for the next parameter - instead you have an eval function.
I states the following earlier:
The common problem is using the singular form
$arg
, which is incorrect.It should always be plural as
$args
.The problem is not that.
In fact,
$arg
can be anything else. The problem was the use of the comma and the parantheses.I run the following code that worked and the output follows:
Code:
Test "ABC" "DEF"
Output:
$var1 value: ABC $var2 value: DEF
You call PowerShell functions without the parenthesis and without using the comma as a separator. Try using:
In PowerShell the comma (,) is an array operator, e.g.
It sets $a to an array with three values.