SSIO
SSIO

Reputation: 55

Switch-Case with multiple Values

I'm writing a code at the moment where I want to install network-shared printers automatically. Which printer the script should install depends on whether a user works for example in Sales or HR. I wanted to solve this problem with a switch statement, but the problem is that it always matches the first value.

I tried several combinations of continue- or break-points, but none of them lead to my desired result.

$a = "HR"

switch ($a) {
    {"Marketing", "Sales"}     { "1" }
    {"Sales Department", "HR"} { "2" }
    "EDV"                      { "3" }
}

Output:

1
2

Normally, the console output should be "2", but it is "1" "2".

Upvotes: 5

Views: 7546

Answers (3)

js2010
js2010

Reputation: 27491

Once you put in a scriptblock on the left side, it becomes more like a where clause.

 $a | where {"Marketing", "Sales"}

Anything returned, like an array of two strings, gets taken as true. This would return 0 as well:

$a = "HR"

switch ($a) {
    {"whatever"}               { "0" }
    {"Marketing", "Sales"}     { "1" }
    {"Sales Department", "HR"} { "2" }
    "EDV"                      { "3" }
}

Another way to make it work:

$a = "HR"

switch ($a) {
    {$_ -eq "Marketing" -or $_ -eq "Sales"}     { "1" }
    {$_ -eq "Sales Department" -or $_ -eq "HR"} { "2" }
    "EDV"                                       { "3" }
}

Or using the -regex option:

$a = "HR"

switch -regex ($a) {
    "Marketing|Sales"     { "1" }
    "Sales Department|HR" { "2" }
    "EDV"                 { "3" }
}

Upvotes: 0

Mark Harwood
Mark Harwood

Reputation: 2415

In response to Mathias's answer, couldn't you also use:

$a = "HR"
switch($a){
    "Marketing"{}
    "Sales"{"1"; break}
    "Sales Department"{}
    "HR"{"2";break}
}

outputs:

2

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

Change the condition block to:

{$_ -in "Marketing", "Sales"}

This way both terms will match the switch case

Upvotes: 6

Related Questions