Powershell-if-else-statement-in-powershell

提供:Dev Guides
移動先:案内検索

Powershell-If Elseステートメント

*if* ステートメントの後にオプションの *else* ステートメントを続けることができます。これは、ブール式がfalseの場合に実行されます。

構文

以下は、if …​ elseステートメントの構文です-

if(Boolean_expression) {
  //Executes when the Boolean expression is true
}else {
  //Executes when the Boolean expression is false
}

ブール式の評価がtrueの場合、コードのifブロックが実行され、そうでない場合はコードのブロックが実行されます。

流れ図

If Elseステートメント

$x = 30

if($x -le 20){
   write-host("This is if statement")
}else {
   write-host("This is else statement")
}

これは、次の結果を生成します-

出力

This is else statement

if …​ elseif …​ elseステートメント

ifステートメントの後にオプションの_else if …​ else_ステートメントを続けることができます。これは、単一のif …​ elseifステートメントを使用してさまざまな条件をテストするのに非常に便利です。

if、elseif、elseステートメントを使用する場合、留意すべき点がいくつかあります。

  • ifには0個または1個のelseを含めることができ、elseifの後に来る必要があります。
  • ifは0個以上のelseifを持つことができ、elseifの前に来る必要があります。
  • else ifが成功すると、残りのelseifもelseもテストされません。

構文

以下は、if …​ elseステートメントの構文です-

if(Boolean_expression 1) {
  //Executes when the Boolean expression 1 is true
}elseif(Boolean_expression 2) {
  //Executes when the Boolean expression 2 is true
}elseif(Boolean_expression 3) {
  //Executes when the Boolean expression 3 is true
}else {
  //Executes when the none of the above condition is true.
}

$x = 30

if($x -eq 10){
   write-host("Value of X is 10")
} elseif($x -eq 20){
   write-host("Value of X is 20")
} elseif($x -eq 30){
   write-host("Value of X is 30")
} else {
   write-host("This is else statement")
}

これは、次の結果を生成します-

出力

Value of X is 30