将参数传递给 PowerShell 函数时的不同行为 [英] Different behaviors while passing parameters to PowerShell function

查看:29
本文介绍了将参数传递给 PowerShell 函数时的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解将参数传递给 PowerShell 中的函数,它在传递单个/多个参数时显示出不同的行为.

I am trying to understand passing parameters to functions in PowerShell and it shows different behavior while passing single/multiple parameters.

有人可以解释为什么会发生这种情况以及正确的做法是什么吗?

can someone explain why it is happening and what is correct way to do it?

Function Add-Numbers($Num1,$Num2){
    return ($Num1 + $Num2);
}

Function SquareIt($Num){
    return ($Num * $Num);
}

# only this adds two numbers correctly
$result1 = Add-Numbers 10 20
write-host "Result1: $result1"; 

#Passing single paramter works this way 
$result2 = SquareIt(15)
write-host "Result2: $result2";

#Passing multiple numbers appends it rather than adding it
$result3 = Add-Numbers(10,20)
write-host "Result3: $result3";

输出:

Result1: 30
Result2: 225
Result3: 10 20 

推荐答案

向函数发送输入值时不使用方括号,因此这两种方法是发送输入的有效方式:

You don't use brackets when sending input values to a function, so these two would be valid ways to send your inputs:

# only this adds two numbers correctly
$result1 = Add-Numbers 10 20
write-host "Result1: $result1"; 

#Passing single paramter works this way 
$result2 = SquareIt 15
write-host "Result2: $result2";

您可以通过命名参数将输入发送到函数,或者它只是假设哪个输入按照提供的顺序映射到哪个输入参数.根据上面的示例,您用空格分隔输入.

You send inputs to a function by either named parameters, or it just assumes which input to map to which input parameter by the order they are provided. You separate inputs with a space, per the examples above.

例如你也可以这样做:

Add-Numbers -Num1 10 -Num2 20
SquareIt -Num 15

使用方括号时不会出错,因为这样做您已将输入转换为数组,然后将其发送到第一个参数.即,基本上你是这样做的:

You don't get an error when using the brackets because by doing so you've turned the input into an array, which then just gets sent to the first parameter. I.e, essentially you did this:

Add-Numbers -Num1 (10,20) -Num2 $null

这篇关于将参数传递给 PowerShell 函数时的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆