Function parameters not working

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 2 years, 2 months ago.

  • Author
    Posts
  • #19634
    Profile photo of albert van wyk
    albert van wyk
    Participant

    Sorry if this has been covered in the forum ....

    take the following function

    Function test ($val1, $Val2)
    {
    Write-Host $Val1

    }

    If I call the function : test("one","two") ,, I get output of one two , and not One only , it would seem that parameter two does not get populated , but parameter 1 ($val1) receives both values ...

    what am I missing ... ?

  • #19635
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    PowerShell functions are called with parameters / arguments separated by spaces, not commas. There are also not any parentheses around the parameter list in the function call.

    ("one", "two") is actually an array which is bound to a single parameter, as you've seen. With your function definition as-is (with two optional parameters that can both be passed by either name or position), here are the legal ways you could call it:

    # no parameters
    test
    
    # two parameters by name
    test -Val1 "one" -Val2 "two"
    
    # two parameters by position
    test "one" "two"
    
    # One parameter by name (either one)
    test -Val1 "one"
    test -Val2 "two"
    
    # One parameter by position (Val1 only)
    test "one"
    
  • #19636
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Check out Get-Help about_Command_Syntax for all the gory details. 🙂

You must be logged in to reply to this topic.