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?
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.
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.
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 :
gettype()
method which gives you the type of an objectGet-Member
CmdLet which help you on properties, and methods of an objectGet-member have many parameters that can help.
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"} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With