Question:
I have an function that fetches data, validates it against a set of user specified parameters and outputs if it is correct or not and based on that takes action, and it works just fine. As a further development of the function I’ve tried to move to a bitwise enumeration for the ‘flags’ but cannot get it to work like i want.
I want to switch through the enumeration and run the case for all possible ‘matches’ but i only get matches on the case when there is only a direct match on the value. Ie. when the value is 1 it runs the case ‘Milk’ but if the value is 3 it will not run the ‘Milk’ and the ‘Bread’ case … i kinda assume its trying to run the ‘Milk, Bread’ case.
Is there any easy way that I’ve failed to see around this? ><
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
[Flags()] enum Breakfast { Nothing = 0 Milk = 1 Bread = 2 Egg = 4 Bacon = 8 } $BreakfastFlag = 3 Switch ([Breakfast]$BreakfastFlag){ Nothing { Write-Host "No breakfast was selected" -ForegroundColor White -BackgroundColor Red } Milk { Write-Host "Milk was selected!" -ForegroundColor White -BackgroundColor DarkGreen } Bread { Write-Host "Bread was selected!" -ForegroundColor White -BackgroundColor DarkGreen } Egg { Write-Host "Egg was selected!" -ForegroundColor White -BackgroundColor DarkGreen } Bacon { Write-Host "Bacon was selected!" -ForegroundColor White -BackgroundColor DarkGreen } } |
Answer:
Yet another variant:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
[Flags()] enum Breakfast { Nothing = 0 Milk = 1 Bread = 2 Egg = 4 Bacon = 8 } $BreakfastFlag = 3 Switch ([Breakfast]$BreakfastFlag) { Nothing { Write-Host "No breakfast was selected" -ForegroundColor White -BackgroundColor Red } { $_ -band [Breakfast]::Milk } { Write-Host "Milk was selected!" -ForegroundColor White -BackgroundColor DarkGreen } { $_ -band [Breakfast]::Bread } { Write-Host "Bread was selected!" -ForegroundColor White -BackgroundColor DarkGreen } { $_ -band [Breakfast]::Egg } { Write-Host "Egg was selected!" -ForegroundColor White -BackgroundColor DarkGreen } { $_ -band [Breakfast]::Bacon } { Write-Host "Bacon was selected!" -ForegroundColor White -BackgroundColor DarkGreen } } |
Output:
1 2 3 4 |
Milk was selected! Bread was selected! >> Script Ended |