22

I am very new to PowerShell scripting and was experimenting with Function. This is the code I wrote:

Function Add
{
   $sum = 0;
   for($i = 0; $i -le $args.length; ++$i)
   {
     [int] $num = $args[$i]
     $sum += $num
   }
   Write-Output "Sum is $sum"
}

And I tried to call using Add 1,2,3. However, when I execute I get the following error:

Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32".

Any idea how to fix this?

2 Answers 2

33

There's a bg trap in Powershell: , is the array operator. Try this at the command line:

PS> 1,2,3

You'll see that it's an array:

PS> (1,2,3).gettype()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

Try to call Add without commas:

PS> Add 1 2 3
Sum is 6

Don't forget everything is an object in Powershell. You are playing on top of .NET.

So you have two friends:

  1. The gettype() method which gives you the type of an object
  2. The Get-Member CmdLet which helps you on properties and methods of an object

Get-member has many parameters that can help.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks..I am from C++ background and didn't think twice before calling function with parameter separated by ,
5

Casting is normally performed assign the type at the right hand side:

$num = [int] $args[$i]

Could be this your problem?


Second observation:

As @JPBlanc has observed, you are passing an array to your function, not three parameters. Use:

Add 1 2 3

and you will get it. Anyway, you don't need casting in this situation. May be in this:

Add "1" "2" "3"

Obviously you can keep calling your function like Add 1,2,3, but you need to change it as follows:

Function Add {
   args[0] | % {$sum=0}{$sum+=$_}{write-output "Sum is $sum"}
}

3 Comments

Look a bit more Empo @Naveen made a newby error he tried to call with an array as parameter in spite of passing parameters.
You'll still need "," when you call object methods with parameters. It's really a trap in powershell newby or coming from any langue.
Yes, that's true. You call object methods with arguments (if any), in the common way, with commas, as you'll do in C#. You call cmdlets with parameters without commas.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.