powershellpowershell-7

Switch not working in a function with two parameters


I am using switch-case in a function with two parameters. It works when there is one parameter, but not when there are two. I am using powershell 7.5.1.

The one that works

function foo([string] $bar) {
    switch ($bar) {
        "hello" {
            write-host "hello world"
        } default {
            write-host "jello world"
        }
    }
}

foo("hello")

Output: hello world

The one that does not work

function foo([string] $bar, [string] $baz) {
    switch ($bar) {
        "hello" {
            write-host "hello world"
        } default {
            write-host "jello world"
        }
    }
}

foo("hello", "something")

Output: jello world

What am I missing here?


Solution

  • In PowerShell, function arguments are separated by spaces, not commas, and you don't enclose them in parentheses unless you're passing an array or an expression that evaluates to multiple arguments.

    Correct way to call the function

    foo "hello" "something"