有人知道怎样才能得到一个具有多个可能值的 switch 语句,像下面的例子一样吗?
switch ($myNumber) {
1 3 5 7 9 { write-host "Odd" }
2 4 6 8 10 {write-host "Even" }
}
在 VBScript 中曾经很容易,所以我确定我只是缺少一些简单的东西。
例如在 VBScript 中
Select Case myNumber
Case 1,3,5,7,9
MsgBox "Odd"
Case 2,4,6,8,10
MsgBox "Even"
End Select
答案1
$myNumber = 3
$arrA = 1, 3, 5, 7, 9
$arrB = 2, 4, 6, 8, 10
switch ($myNumber) {
{$arrA -contains $_} { write-host "Odd" }
{$arrB -contains $_} { write-host "Even" }
}
答案2
对于你的情况你可以简单地使用
switch ($myNumber) {
{ $_ % 2 -eq 1 } { "Odd" }
{ $_ % 2 -eq 0 } { "Even" }
}
实际尝试模拟在 VB 中可以做什么可能类似于
switch ($myNumber) {
{ 1,3,5,7,9 -contains $_ } { "Odd" }
{ 2,4,6,8,10 -contains $_ } { "Even" }
}
答案3
switch ($myNumber) {
{$_ -in 1, 3, 5, 7, 9} { write-host "Odd" }
{$_ -in 2, 4, 6, 8, 10} {write-host "Even" }
}
答案4
如何使用一个简单的替代方案正则表达式?
switch -regex ($myNumber)
{
"^[13579]$" { Write-Host "Odd" }
"^([2468]|10)$" { Write-Host "Even" }
default { Write-Host "Other" }
}