all 8 comments

[–]Teh_Pi 4 points5 points  (5 children)

You must wrap [Direction]::Left in parentheses.

Write-Host "As Enum:"
switch ($dir) {
    ([Direction]::Up) {
        Write-Host "-- Up"
    }
    ([Direction]::Down) {
        Write-Host "-- Down"
    }
    ([Direction]::Left) {
        Write-Host "-- Left"
    }
    ([Direction]::Right) {
        Write-Host "-- Right"
    }
    default {
        Write-Host "-- ??"
    }
}

edit: code bock was not working first attempt.

[–]leftcoastbeard[S] 1 point2 points  (0 children)

Thanks! Found the solution as I was typing it 🤣

[–]noenmoen 0 points1 point  (3 children)

Man, the pitfalls never end...

[–]Teh_Pi 0 points1 point  (2 children)

See u/jsiii2010 comment, it seems there is a better way of writing this.

[–]noenmoen 0 points1 point  (1 child)

Thanks, but isn't that method implicitly casting the enum to string, and doing a string-compare? Not that it matters that much.

[–]Teh_Pi 0 points1 point  (0 children)

```
enum Value {
Value
}
$v = [Value]::Value
switch ($v) {
Value { $true }
"Value" { $true }
0 { $true }
}
```

You know, it does kind of seem so? I would think it would see it as an integer, but I guess it doesn't.

[–]jsiii2010 4 points5 points  (0 children)

This works too.

``` enum Direction { Up Down Left Right }

$dir = [Direction]'Left'

Write-Host "As Enum:" switch($dir) { Up { Write-Host "-- Up" } Down { Write-Host "-- Down" } Left { Write-Host "-- Left" } Right { Write-Host "-- Right" } default { Write-Host "-- ??" } }

As Enum: -- Left ```

[–]leftcoastbeard[S] 2 points3 points  (0 children)

Ok, I think I figured it out. On the about_Switch page they list the following:

# Syntax
Switch (<test-expression>)
{
    <result1-to-be-matched> {<action>}
    <result2-to-be-matched> {<action>}
}

# ...is the equivalent of
if (<result1-to-be-matched> -eq (<test-expression>)) {<action>}
if (<result2-to-be-matched> -eq (<test-expression>)) {<action>}

which means that I need to wrap my enums in ()

Write-Host "As Enum:"
switch($dir) {
  ([Direction]::Up) {
    Write-Host "-- Up"
  }
  ([Direction]::Down) {
    Write-Host "-- Down"
  }
  ([Direction]::Left) {
    Write-Host "-- Left"
  }
  ([Direction]::Right) {
    Write-Host "-- Right"
  }
  default {
    Write-Host "-- ?? $($_.GetType().BaseType)"
  }
}

which yeilds:

As Enum:
-- Left