2

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.

Varden
  • 101
  • 5
  • 1
    Casting individual arguments to `[int]` is unnecessary - PowerShell does that for you :-) – Mathias R. Jessen Jan 03 '21 at 18:03
  • PowerShell functions, cmdlets, scripts, and external programs must be invoked _like shell commands_ - `foo arg1 arg2` - _not_ like C# methods - `foo('arg1', 'arg2')`. If you use `,` to separate arguments, you'll construct an _array_ that a command sees as a _single argument_. To prevent accidental use of method syntax, use [`Set-StrictMode -Version 2`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/set-strictmode) or higher, but note its other effects. See [this answer](https://stackoverflow.com/a/65208621/45375) for more information. – mklement0 Jan 03 '21 at 19:05

1 Answers1

3

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 learn.microsoft.com link.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Moerwald
  • 10,448
  • 9
  • 43
  • 83
  • Thanks for your answer, I knew it had to be a syntax question, but I'm new to powershell and have C # reflexes. Thanks to you. – Varden Jan 04 '21 at 10:47