1

An example of what I want to do:

    enum Fruit {
        Apple
        Banana
        Orange
    }

    $myFruit = [Fruit]::$UsrString

    switch ($myFruit) {
        Apple, Orange {
        Write-Host "This is an apple or an orange"
        break
        }
        Banana {
        Write-Host "This is a banana"
        break
        }
        default {
        Write-Host "Unknown fruit: $myFruit"
        break
        }
    }

But each attempt I have made has yet to work as intended, if at all.

I have searched for anything to do with Powershell, switch-statements, and enums but have yet to find the answer.

I have reviewed this link on StackOverflow.

I have successfully used the "switch -regEx (someEnum)" as long as I use the integer values of the enum items. However, that essentially defeats the use of the enum (ie. labeled ints).

My intent was to keep the switch as efficient as possible (ie. switching on simple int values; staying away from the more common string-compare style PS switch usage, just to keep performance up).

Does the multi-item case block syntax exist for enum usage in powershell?

Thanks in advance for any information.

BentChainRing
  • 382
  • 5
  • 14

1 Answers1

2

The switch statement:

  • does not support multiple branch conditions, but ...

  • does support using a script block ({ ... }) as a branch condition, inside of which you're free to perform any test, including for multiple values, using the automatic $_ variable to refer to the input value at hand.

Therefore:

switch ($myFruit) {
  { $_ -in 'Apple', 'Orange' } {
    "This is an apple or an orange"
    break
  }
  Banana {
    "This is a banana"
    break
  }
  default {
    "Unknown fruit: $_"
  }
}

Note:

  • As you can see in the default branch's action script block above, $_ also refers to the input value there.

    • Using $_ is generally preferable, as the switch input value can be an array (list-like collection), in which case the branches are evaluated for each element (and $_ then refers to the element at hand.

    • With an array as input, use continue in lieu of break in an action script block in order to continue processing with the next element (break will prevent processing of further elements).

  • Note that even though the [Fruit] enumeration values are compared against strings, the comparison works, because PowerShell conveniently automatically converts enumeration values to and from their string representations.

mklement0
  • 382,024
  • 64
  • 607
  • 775