Different behaviors while passing parameters to PowerShell function

假如想象 提交于 2021-02-05 07:49:11

问题


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";

Output:

Result1: 30
Result2: 225
Result3: 10 20 

回答1:


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.

So for example you could also do:

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


来源:https://stackoverflow.com/questions/59303267/different-behaviors-while-passing-parameters-to-powershell-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!