about_Do

適用於: Windows PowerShell 2.0, Windows PowerShell 3.0, Windows PowerShell 4.0, Windows PowerShell 5.0

在此插入簡介。

主題

about_Do

簡短描述

根據 While 或 Until 條件,執行陳述式清單一次或多次。

詳細描述

Do 關鍵字會根據條件,搭配 While 關鍵字或 Until 關鍵字來執行指令碼區塊中的陳述式。不同於相關的 While 迴圈,Do 迴圈中的指令碼區塊一律會至少執行一次。

Do-While 迴圈是一種 While 迴圈。在 Do-While 迴圈中,會在執行指令碼區塊之後評估條件。就像是在 While 迴圈中一樣,只要條件評估為 true,就會重複執行指令碼區塊。

如同 Do-While 迴圈,Do-Until 迴圈一律會至少執行一次,再評估條件。不過,只有在條件為 false 時,才會執行指令碼區塊。

Continue 和 Break 流程控制關鍵字可用於 Do-While 迴圈或 Do-Until loop 迴圈中。

語法

以下顯示 Do-While 陳述式的語法:

do {<statement list>} while (<condition>)

以下顯示 Do-Until 陳述式的語法:

do {<statement list>} until (<condition>)

陳述式清單包含每次進入或重複迴圈時所執行的一或多個陳述式。

陳述式的條件部分會解析為 true 或 false。

範例

下列 Do 陳述式範例會計算陣列中的項目,直到已達值為 0 的項目為止。

          C:\PS> $x = 1,2,78,0
          C:\PS> do { $count++; $a++; } while ($x[$a] -ne 0) 
          C:\PS> $count
          3

下列範例使用 Until 關鍵字。請注意,不等於運算子 (-ne) 會取代為等於運算子 (-eq)。

          C:\PS> $x = 1,2,78,0
          C:\PS> do { $count++; $a++; } until ($x[$a] -eq 0) 
          C:\PS> $count
          3

下列範例會寫入陣列的所有值,並略過任何小於零的值。

          do
          {
              if ($x[$a] -lt 0) { continue }
              Write-Host $x[$a]
          } 
          while (++$a -lt 10)

另請參閱

about_While

about_Operators

about_Assignment_Operators

about_Comparison_Operators

about_Break

about_Continue