Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type conversion problem in a PowerShell function

Tags:

powershell

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?

like image 752
Naveen Avatar asked May 15 '11 06:05

Naveen


People also ask

How do you change a datatype in PowerShell?

The rules for converting any value to type byte, int, or long are as follows: The bool value False is converted to zero; the bool value True is converted to 1. A char type value whose value can be represented in the destination type has that value; otherwise, the conversion is in error.

How do I convert a string to an int in PowerShell?

Use [int] to Convert String to Integer in PowerShell The data type of $a is an integer . But when you enclose the value with " " , the data type will become string . To convert such string data type to integer, you can use [int] as shown below.


2 Answers

Big TRAP in Powershell "," is the array operator just try at the command line :

PS> 1,2,3

You'll see the array

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

So try to call :

PS> Add 1 2 3
Sum is 6

And don't forget everithing is OBJECT in Powershell you are playing on the top of .NET

So you've got two freinds :

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

Get-member have many parameters that can help.

like image 94
JPBlanc Avatar answered Sep 17 '22 14:09

JPBlanc


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"}
}
like image 31
Emiliano Poggi Avatar answered Sep 20 '22 14:09

Emiliano Poggi