Reputation: 527
I just created a simple function "f" that adds an pscustomobject element into an arraylist, but when displaying it, result is not what I expected:
$c=New-Object System.Collections.ArrayList($null)
function f([string]$a1,[string]$a2)
{
$c.Add([PSCustomObject]@{item1=$a1;item2=$a2})
}
f("kkk","aaa")
$c
result is:
item1 item2
----- -----
kkk aaa
It seems to me that both "kkk" and "aaa" goes to item1, if I type
$c.item1
it prints
kkk aaa
Why? I expect item1 to be "kkk" and item2 to be "aaa".
Upvotes: 0
Views: 1625
Reputation: 36277
Ok, as suggested, making an answer. Kayasax really did give the correct answer, even if he didn't help you fix the problem. The reason that both of those strings are assigned to the first property is because you have called your function incorrectly. You have effectively passed 1 argument to the function, that being an array containing two strings. To properly pass multiple arguments to the function either specify them by name (derived by the variable you assign the parameter to within the function, or any declared aliases), or you can pass them without naming them in the order that they are declared in the function, separated by a space.
In your code you are effectively doing this:
f -a1 ("kkk","aaa") -a2
To correct the problem you can either pass the arguments by position:
f "kkk" "aaa"
Or you can pass the arguments by name (order does not matter when passing by name):
f -a1 "kkk" -a2 "aaa"
Doing either of those will result in your desired output.
Upvotes: 1
Reputation: 26120
have a look at the the powershell gotchas here : https://stackoverflow.com/tags/powershell/info
PowerShell separates function arguments with spaces, not commas.
for those who don't read comments @TheMadTechnician gave you the two correct ways of calling function with arguments in PS :
f "kkk" "aaa"
or f -a1 "kkk" -a2 "aaa"
Upvotes: 2