Powershell - 将两个变量一起添加到命令行接收数字

时间:2014-07-21 16:44:49

标签: windows powershell

我正在尝试从命令行接收输入,例如添加两个数字,但我要么返回文字变量编号,数字0,要么返回无效数据。

使用此代码:

Param (
    [int]$a, 
    [int]$b
)
function add([int]$a,[int]$b)
{
    $var = $a+"$b"
    $a
    $b
    $var
    return $a + $b
}

add([int]$a,[int]$b)

这是我收到的错误。

PS C:\> .\add.ps1 -a 5 -b 4
add : Cannot process argument transformation on parameter 'a'. Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32".
At C:\add.ps1:15 char:4
+ add <<<< ([int]$a,[int]$b)
    + CategoryInfo          : InvalidData: (:) [add], ParameterBindin...mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,add

然后用

Param (
    [int]$a, 
    [int]$b
)
function add([int]$a,[int]$b)
{
    $var = $a+"$b"
    $a
    $b
    $var
    return $a + $b
}

add

它只返回0。然后当我使用这段代码时:

Param (
    [int]$a, 
    [int]$b
)
function add($a,$b)
{
    $var = $a+"$b"
    $a
    $b
    $var
    return $a + $b
}

add($a,$b)

它只返回我作为命令行参数提供的内容。我这样称呼这个程序:

.\add.ps1 -a 5 -b 4

我必须做一些与Powershell无法正确对待的事情。但是,我不确定哪些术语,或者我应该如何说出我的搜索,因为我知道如何连接变量,或者只是添加普通整数,而不是在函数中添加从命令行传递的整数的两个变量。

2 个答案:

答案 0 :(得分:2)

您可能不想重复使用变量名称,因为这会让人感到困惑。我将函数中的变量更改为$c$d。然后调用函数就像你调用脚本一样,它工作得很好......

Param (
    [int]$a, 
    [int]$b
)
function add([int]$c,[int]$d)
{
    $var = $c+$d
    $c
    $d
    $var
    return $d + $c
}

add -c $a -d $b

PS C:\test> .\add.ps1 -a 5 -b 4
5
4
9
9

答案 1 :(得分:2)

function(argument1, argument2)不是调用powershell函数的正确语法。调用不带参数名称的PowerShell函数的正确语法是function argument1 argument2

您正在做什么

add([int]$a,[int]$b)

使用单个数组参数提供 add 函数 - 该数组是无法转换为错误消息中提到的Int32的对象。换句话说,您提供数组([int]$a,[int]$b)作为添加功能 $ a 参数的值,而不提供添加功能 $ b 参数的值。*

此外,PowerShell是一种动态类型语言;您无需在函数调用中将 $ a $ b 的参数强加为 [int] ,尤其是因为您已经将它们放在 param 列表中。将最后一行更改为:

add $a $b

如果由于某种原因你确实希望将参数转换为函数调用,你可以通过独立地将每个转换作为表达式进行评估来实现:

add ([int]$a) ([int]$b)

<小时/> *为了说明这一点,请将添加功能更改为:

function add($a, $b)
{
  "`nValue of parameter A:"
  $a
  "`nType of parameter A:"
  $a.GetType()
  "`nValue of parameter B:"
  $b
  "`nType of parameter B:"
  $b.GetType()
}

当你用

打电话时
add([int]$a,[int]$b)

您会得到以下结果,表示 A 是两个整数的数组,并且未定义 B

Value of parameter A:
4
5

Type of parameter A:

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

Value of parameter B:

Type of parameter B:
You cannot call a method on a null-valued expression.
At C:\Data Files\scratch\so\soscratch\add.ps1:15 char:3
+   $b.GetType()
+   ~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull