
- PowerShell 教程
- PowerShell - 首頁
- PowerShell - 概述
- PowerShell - 環境設定
- PowerShell - Cmdlet
- PowerShell - 檔案和資料夾
- PowerShell - 日期和時間
- PowerShell - 檔案 I/O
- PowerShell - 高階 Cmdlet
- PowerShell - 指令碼
- PowerShell - 特殊變數
- PowerShell - 運算子
- PowerShell - 迴圈
- PowerShell - 條件語句
- PowerShell - 陣列
- PowerShell - 雜湊表
- PowerShell - 正則表示式
- PowerShell - 反引號
- PowerShell - 方括號
- PowerShell - 別名
- PowerShell 有用資源
- PowerShell - 快速指南
- PowerShell - 有用資源
- PowerShell - 討論
PowerShell - switch 語句
switch 語句允許將變數與一個值的列表進行相等性測試。每個值稱為一個 case,並且正在切換的變數會針對每個 case 進行檢查。
語法
增強型 for 迴圈的語法如下:
switch(<test-value>) { <condition> {<action>} break; // optional <condition> {<action>} break; // optional <condition> {<action>} break; // optional }
以下規則適用於switch 語句:
在 switch 語句中使用的變數只能是任何物件或物件陣列。
您可以在一個 switch 中擁有任意數量的 case 語句。每個 case 後面都跟著可選的操作。
case 的值必須與 switch 中變數的資料型別相同,並且必須是常量或字面量。
當正在切換的變數等於某個 case 時,該 case 後面的語句將執行,直到遇到break 語句。
當遇到break 語句時,switch 將終止,並且控制流跳轉到 switch 語句後面的下一行。
並非每個 case 都需要包含 break。如果沒有出現 break,則控制流將貫穿到後續的 case,直到遇到 break。
流程圖

示例 1
不帶 break 語句的 Switch 語句示例。
switch(3){ 1 {"One"} 2 {"Two"} 3 {"Three"} 4 {"Four"} 3 {"Three Again"} }
這將產生以下結果:
輸出
Three Three Again
示例 2
帶 break 語句的 Switch 語句示例。
switch(3){ 1 {"One"} 2 {"Two"} 3 {"Three"; break } 4 {"Four"} 3 {"Three Again"} }
這將產生以下結果:
輸出
Three
示例 3
以陣列作為輸入的 Switch 語句示例。
switch(4,2){ 1 {"One"} 2 {"Two"} 3 {"Three"; break } 4 {"Four"} 3 {"Three Again"} }
這將產生以下結果:
輸出
Four Two
powershell_conditions.htm
廣告