Powershell - 如果,否則語句



在布林表示式為 false 時執行的 if 語句後可以緊跟一個可選的 else 語句。

語法

下面是 if...else 語句的語法:

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

如果布林表示式求值為 true,則將執行 if 程式碼塊,否則將執行 else 程式碼塊。

流程圖

If Else Statement

示例

$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 可以沒有 else 或只有一個 else,並且必須放在任何 elseif 之後。

  • if 可以有零個到多個 elseif,並且必須放在 else 之前。

  • 一旦 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
powershell_conditions.htm
廣告