Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to target multiple conditions with a single switch match in PowerShell?

Tags:

powershell

In an example script, I want to execute one block of code if my variable matches 1, another one if it matches 2, 3, 5, or 8, and a different block for 4, 6, or 7.

I'd like to do something like this:

switch($x)
{
    1 {'Condition 1'}
    2 -or 3 -or -5 -or 8 {'Condition 2'}
    4 -or 6 -or 7 {'Condition 3'}
}

But this doesn't work. Is there a way to do this sort of work with switch, without having to spell out all 8 options individually, or are multiple if statements the only way to go?

like image 657
Iszi Avatar asked Dec 19 '22 20:12

Iszi


1 Answers

Another option, if you want to treat the values as numbers instead of strings:

switch ($x)
{
    1                {'Condition 1'}
    {$_ -in 2,3,5,8} {'Condition 2'}
    {$_ -in 4,6,7}   {'Condition 3'}
}
like image 53
Keith Hill Avatar answered May 12 '23 07:05

Keith Hill