Type conversion problem in a PowerShell function
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 $ar开发者_JS百科gs.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?
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:
- The
gettype()
method which gives you the type of an object - The
Get-Member
CmdLet which helps you on properties and methods of an object
Get-member
has 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"} }
精彩评论