Different behaviors while passing parameters to PowerShell function

后端 未结 1 1879
暗喜
暗喜 2021-01-26 23:46

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

can someone explain

相关标签:
1条回答
  • 2021-01-27 00:01

    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
    
    0 讨论(0)
提交回复
热议问题