2016-07-12 16 views
1

PowerShellでSwitchステートメントをテストする簡単なコードを試しています。 Switchステートメントで処理される条件のいずれにも該当しない条件に対して、正しいスクリプトブロックを実行していません。例えばスイッチでPowerShellで正しい結果が得られない

$Age = Read-Host "Age" 

Switch ($Age) 
{ 
    { (($_ -gt 0) -and ($_ -le 25)) } { Write-Host "You are too young" } 
    { (($_ -gt 25) -and ($_ -le 50)) } { Write-Host "You are still young" } 
    { (($_ -gt 50) -and ($_ -le 75)) } { Write-Host "You are Closer to your death" } 
    { (($_ -gt 75) -and ($_ -le 99)) } { Write-Host "I am surprised you are still alive" } 
    Default { "Invalid age" } 
} 

:あなたが入力-12または110 $Ageパラメータの値として、それはデフォルトのブロック(無効歳)を実行する必要がありますが、それは最初の条件を実行している場合。

Age: -12 
You are too young 

Age: 110 
You are too young 

ただし、0-99の間の他の値でも正しく動作します。

Age: 12 
You are too young 

Age: 30 
You are still young 

Age: 55 
You are Closer to your death 

Age: 88 
I am surprised you are still alive 

ここで間違っていることをお伝えできますか?

答えて

3

これはPowershellが動的に型指定されているために発生します。変数$Ageは、あいまいさを増やす文字列または整数(または何か他のもの)である可能性があります。これと同様に、変数intを作るために

$Age = Read-Host "Age" 
Age: 110 
PS C:\> $Age.GetType() 

IsPublic IsSerial Name          BaseType 
-------- -------- ----          -------- 
True  True  String         System.Object 

$Age = Read-Host "Age" 
Age: 55 
PS C:\> $Age.GetType() 

IsPublic IsSerial Name          BaseType 
-------- -------- ----          -------- 
True  True  Int32         System.ValueType 

は、そのように宣言します。

[int]$Age = Read-Host "Age" 
Age: 110 
PS C:\> $Age.GetType() 

IsPublic IsSerial Name          BaseType 
-------- -------- ----          -------- 
True  True  Int32         System.ValueType 
+2

別のアプローチは、 '(-gt 0 $ _)'順序を交換することです - (> ' 0 -lt $ _) 'のように、暗黙的なキャスティングは右のものと左のものを一致させる傾向があるため、左に番号を付けます。 – TessellatingHeckler

+0

うわー!!優れた。それは完全に機能します。データ型の問題を指摘していただきありがとうございます。私はそれがうまくいくとは考えていませんでした。 – SavindraSingh

関連する問題