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

PowerShell 深度探索(十):迴圈語句全攻略——For、Foreach、While、Do Until

     編輯:關於.NET

PowerShell 迴圈語句一覽

語句語法適用場景
forfor (初始; 條件; 遞增) { 程式碼 }已知迴圈次數、計數器控制
foreachforeach ($item in $collection) { 程式碼 }遍歷集合/陣列每個元素
ForEach-Object$collection | ForEach-Object { 程式碼 }管線串流處理、記憶體效率佳
whilewhile (條件) { 程式碼 }條件為真持續執行、次數未知
do-whiledo { 程式碼 } while (條件)至少執行一次,再判斷條件
do-untildo { 程式碼 } until (條件)至少執行一次,直到條件為真

實戰範例

1. Foreach 查詢硬體資訊

磁碟資訊

$DiskDrive = Get-WmiObject -Class Win32_DiskDrive -Namespace root\CIMV2
foreach ($item in $DiskDrive) {
    Write-Host "Description: " $item.Description
    Write-Host "Device ID: " $item.DeviceID
    Write-Host "Interface: " $item.InterfaceType
    Write-Host "Model: " $item.Model
    Write-Host "Size: " $item.Size
    Write-Host "Status: " $item.Status
}

磁碟資訊輸出

處理器資訊

$Processor = Get-WmiObject -Class Win32_Processor -Namespace root\CIMV2
foreach ($item in $Processor) {
    Write-Host "Name: " $item.Name
    Write-Host "Cores: " $item.NumberOfCores
    Write-Host "Clock: " $item.CurrentClockSpeed "MHz"
    Write-Host "L2 Cache: " $item.L2CacheSize "KB"
}

CPU 資訊輸出

2. While 監控程序回應

Notepad
While (Get-Process -Name Notepad | Select-Object -ExpandProperty Responding) {
    Start-Sleep -Seconds 1
}
$time = Get-Date
Write-Host "Notepad stopped responding at: $time"

當記事本停止回應時輸出時間戳記。

3. Do-While 同樣邏輯

Notepad
Do { Start-Sleep -Seconds 1 }
While (Get-Process -Name Notepad | Select-Object -ExpandProperty Responding)
$time = Get-Date
Write-Host "Notepad stopped responding at: $time"

4. Do-Until 互動式選單

Do {
    "Quit Now? (Y/N)"
    $input = Read-Host
} Until ($input -eq "Y")

互動選單示範

5. ForEach-Object 格式化輸出實戰

處理固定寬度文字資料,轉換為結構化輸出:

${C:\test.txt} | ForEach-Object {
    $total = 0; $id = 1
} {
    [void]($_ -match '^.{3}(?<id>\d+)(?<name>[\p{IsCJKUnifiedIdeographs}]+)(?<salary>[\d.]*)')
    $ofs = '|'
    "$($id;$id++;$matches.id;$matches.name;'{0:f2}' -f [float]$matches.salary)"
    $total += $matches.salary
} {
    "`tSubtotal`t`t|$total"
}

格式化輸出結果

此例展示正則表達式命名捕捉群組、格式化字串、累加計算等進階技巧。

選擇指南

  • 已知次數/計數器 → for
  • 記憶體中集合遍歷 → foreach(效能最佳)
  • 大量資料/管線串流 → ForEach-Object(串流處理、低記憶體)
  • 條件控制、監控 → while / do-while
  • 至少執行一次、選單互動 → do-until

效能提示

  • foreach 陳述式比 ForEach-Object 快 2-3 倍,但需將集合完整載入記憶體
  • 處理大型檔案/資料流時優先考慮 ForEach-Object 或 Switch -File
  • 避免在迴圈內重複建立昂貴物件,移至迴圈外

靈活運用各類迴圈,配合管線特性,能編寫出高效且易讀的 PowerShell 自動化腳本。

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