Nerdtron
Nerdtron

Reputation: 1516

error when calling function with 2 integer args

I'm defining a function in PowerShell and trying to call it as shown below.

function foo([Int32] $a, [Int32] $b)
{
}
foo(0,0)

When I do this, I get the following error.

foo : Cannot process argument transformation on parameter 'a'. Cannot convert the "System.Object[]" value of type "System.Object[]" to type
 "System.Int32".
At line:1 char:4
+ foo <<<< (0,0)
    + CategoryInfo          : InvalidData: (:) [foo], ParameterBindin...mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,foo

If I change the function to only accept a single argument as shown below it works fine.

function foo([Int32] $a)
{
}
foo(0)

Or, if I remove the type info it also works as shown below.

function foo($a, $b)
{
}
foo(0,0)

What's wrong with the first version? How do I properly define a function which takes multiple integer arguments?

EDIT: Interestingly, the following invocation does work.

foo 0 0

I'd prefer the ()s though and am wondering how to get it to work with those.

Upvotes: 4

Views: 3623

Answers (2)

bala
bala

Reputation: 1

Function MyFunction ([int32]$arg1,[int32]$arg2)
 {


  $data= $arg1+$arg2 
 return $data 


 }

MyFunction 2 4

Upvotes: 0

CB.
CB.

Reputation: 60938

In powershell parameters are passed without parenthesis try:

foo 0 0

doing

foo(0,0)

you are passing an object array as first parameter.

You can pass the array and then split each value as parameter inside the script, but why do it?

Upvotes: 14

Related Questions