Powershell | Passing array element to function

Viewed 488

I'm trying to learn Powershell to make script at work and I'm stuck on a simple task. I've search google before but all I get is how to pass the entire array to my function, but I just want to pass one element of the array :

function test
{
    param ([int]$a, [int]$b)
    $a
    $b
}

$tab = "4", "8", "15", "16", "23", "42"

test(([int]($tab[1])), ([int]($tab[4])))

Here what the error I get (sorry I had to translate to english from french :

test: Unable to process the transformation of argument on parameter "a". Failed to convert value "System.Object []" from type "System.Object []" to type "System.Int32".
+ test(([int]($tab[1])), ([int]($tab[4])))
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData : (:) [test], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,test

I don't understand why he sees a "System.Object []" when I pass an Int. If I do a "GetType()" before passing to the function, I get the correct Type. Do I have to pass the entire array and get the element in the function or is there a solution ?

Thanks in advance for your answers.

1 Answers

In Powershell the , is the array operator. Therefore you've to call your method in a different way. Either via:

 test $tab[1] $tab[4]

or via parameter names:

  test -a $tab[1] -b $tab[4]

If you call the test function via the ,-operator:

 test $tab[1], $tab[4]

Powershell generates an array containing $tab[1] and $tab[4], and tries to bind that array to the first parameter of your method.

This also explains the error Failed to convert value "System.Object []" from type "System.Object []" to type "System.Int32".. Here PowerShell tries to convert the generated array to System.Int32 via the default type conversion rules. Since none of them fits Powershell states an error.

You'll find more information about PowerShell functions under this docs.microsoft.com link.

Related