首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

PowerShell 深度探索(九):條件判斷與邏輯控制——If、Switch 完整指南

     編輯:關於.NET

比較運算子

PowerShell 預設不區分大小寫,亦提供區分大小寫版本:

運算子意義區分大小寫版本忽略大小寫版本
-eq等於-ceq-ieq
-ne不等於-cne-ine
-gt大於-cgt-igt
-ge大於等於-cge-ige
-lt小於-clt-ilt
-le小於等於-cle-ile
-like萬用字元比對-clike-ilike
-match正則比對-cmatch-imatch
-contains集合包含-ccontains-icontains
-in值在集合中-cin-iin

示範

"MaRui" -eq "marui"    # True
"MaRui" -ieq "MARUI"   # True
"MaRui" -ceq "MARUI"   # False

邏輯運算子

  • -and:邏輯 AND
  • -or:邏輯 OR
  • -not、!:邏輯 NOT

If / ElseIf / Else 陳述式

語法

if (條件) { 程式碼 }
elseif (條件) { 程式碼 }
else { 程式碼 }

基本範例

$n = 10
if ($n -eq 1) { "n=1" }
elseif ($n -ne 1) { "n!=1, and n=$n" }

If 執行結果

實戰:偵測作業系統版本

$ComputerName = (Get-WmiObject Win32_ComputerSystem).Name
$OS_Version = (Get-WmiObject Win32_OperatingSystem -ComputerName $ComputerName).Version

if (($OS_Version -eq "5.1.2600") -or ($OS_Version -eq "5.2.3790")) {
    Write-Host "Computer: $ComputerName"
    if ($OS_Version -eq "5.1.2600") { Write-Host "OS: Windows XP" }
    elseif ($OS_Version -eq "5.2.3790") { Write-Host "OS: Windows Server 2003" }
}
elseif (($OS_Version -eq "5.0.2195") -or ($OS_Version -eq "6.1.7600")) {
    Write-Host "Computer: $ComputerName"
    if ($OS_Version -eq "5.0.2195") { Write-Host "OS: Windows 2000 Server" }
    elseif ($OS_Version -eq "6.1.7600") { Write-Host "OS: Windows 7" }
}
else {
    Write-Host "$ComputerName is not supported."
}
"-- END OF REPORT --"

OS 偵測輸出

Switch 陳述式

語法

Switch (測試值) {
    比對值1 { 程式碼 }
    比對值2 { 程式碼 }
    Default { 預設程式碼 }
}

數值比對範例:網域角色判斷

Switch ((Get-WmiObject Win32_ComputerSystem).DomainRole) {
    0 { "Standalone Workstation" }
    1 { "Member Workstation" }
    2 { "Standalone Server" }
    3 { "Member Server" }
    4 { "Backup Domain Controller" }
    5 { "Primary Domain Controller" }
    Default { "Cannot determine domain role" }
}

運算式比對範例

Switch (100) {
    (99 + 1)   { "99+1=100" }
    (1 + 100)  { "1+100=100" }
    (50 * 2)   { "50*2=100" }
    (33.333*3) { "33.333*3=100" }
}

Switch 運算式比對結果

注意:Switch 會評估所有符合條件的區塊,不只第一個(除非使用 Break)。

進階 Switch 參數

  • -Regex:比對值視為正則表達式
  • -Wildcard:比對值視為萬用字元模式
  • -CaseSensitive:區分大小寫
  • -File:逐行讀取檔案進行比對

檔案處理範例

Switch -Regex -File "log.txt" {
    "ERROR"   { Write-Host "Error found: $_" -ForegroundColor Red }
    "WARN"    { Write-Host "Warning: $_" -ForegroundColor Yellow }
    "INFO"    { Write-Host "Info: $_" }
}

最佳實務

  1. 簡單雙向分支用 If/Else
  2. 多重數值/列舉比對用 Switch(可讀性佳、效能好)
  3. 複雜複合條件用 If/ElseIf
  4. 善用 -CaseSensitive 明確控制比對行為
  5. 避免深層巢狀,提早返回或使用 Switch 簡化邏輯

掌握條件與邏輯控制,是編寫健壯自動化腳本的基石。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved