分享方式:


about_For

簡短描述

描述您可以用來根據條件式測試執行語句的語言命令。

詳細描述

For語句(也稱為迴圈)是一種For語言建構,可用來建立迴圈,以在指定條件評估為 $true時,在命令區塊中執行命令。

迴圈的 For 一般用法是逐一查看值陣列,並在這些值的子集上運作。 在大部分情況下,如果您想要反覆運算數位中的所有值,請考慮使用 Foreach 語句。

語法

以下顯示 For 語句語法。

for (<Init>; <Condition>; <Repeat>)
{
    <Statement list>
}

Init 佔位元代表在循環開始之前執行的一或多個命令。 您通常會使用 語句的 Init 部分來建立和初始化具有起始值的變數。

接著,這個變數將會是語句下一個部分中 For 要測試之條件的基礎。

Condition 佔位符代表解析為 $true$false 布爾值的 語句部分For 每次迴圈執行時, For PowerShell 都會評估條件。 如果語句為 $true,則命令區塊中的命令會執行,並再次評估 語句。 如果條件仍然$true為 ,語句清單中的命令會再次執行。 迴圈會重複,直到條件變成 $false為止。

Repeat 佔位元代表一或多個命令,並以逗號分隔,每次迴圈重複時都會執行。 一般而言,這是用來修改在 語句之 Condition 部分內測試的變數。

語句清單佔位元代表每次輸入或重複迴圈時執行的一或多個命令集合。 語句清單的內容會以大括弧括住。

支援多個作業

Init 語句中的多個指派作業支援下列語法:

# Comma separated assignment expressions enclosed in parentheses.
for (($i = 0), ($j = 0); $i -lt 10; $i++)
{
    "`$i:$i"
    "`$j:$j"
}

# Sub-expression using the semicolon to separate statements.
for ($($i = 0;$j = 0); $i -lt 10; $i++)
{
    "`$i:$i"
    "`$j:$j"
}

Repeat 語句中的多個指派作業支援下列語法:

# Comma separated assignment expressions.
for (($i = 0), ($j = 0); $i -lt 10; $i++, $j++)
{
    "`$i:$i"
    "`$j:$j"
}

# Comma separated assignment expressions enclosed in parentheses.
for (($i = 0), ($j = 0); $i -lt 10; ($i++), ($j++))
{
    "`$i:$i"
    "`$j:$j"
}

# Sub-expression using the semicolon to separate statements.
for ($($i = 0;$j = 0); $i -lt 10; $($i++;$j++))
{
    "`$i:$i"
    "`$j:$j"
}

注意

前置或後置遞增以外的作業可能無法搭配所有語法使用。

針對多個 條件 ,請使用邏輯運算符,如下列範例所示。

for (($i = 0), ($j = 0); $i -lt 10 -and $j -lt 10; $i++,$j++)
{
    "`$i:$i"
    "`$j:$j"
}

如需詳細資訊,請參閱 about_Logical_Operators

語法範例

語句至少For需要語句周圍 InitConditionRepeat 部分的括弧,以及語句的語句清單部分以大括弧括住的命令。

請注意,即將推出的範例會刻意在語句之外 For 顯示程序代碼。 在稍後的範例中,程式代碼會整合到 語句中 For

例如,下列 For 語句會持續顯示變數的值 $i ,直到您按 CTRL+C 手動中斷命令為止。

$i = 1
for (;;)
{
    Write-Host $i
}

您可以將其他命令新增至語句清單,以便每次執行循環時,的值 $i 會遞增 1,如下列範例所示。

for (;;)
{
    $i++; Write-Host $i
}

在您按 CTRL+C 中斷命令之前,此語句會持續顯示變數的值 $i ,因為每次執行循環時會遞增 1。

您可以改用 語句的 Repeat 部分For,而不是變更 語句清單部分For的變數值,如下所示。

$i=1
for (;;$i++)
{
    Write-Host $i
}

此語句仍會無限期地重複,直到您按 CTRL+C 中斷命令為止。

您可以使用條件終止For迴圈。 您可以使用 語句的 For Condition 部分來放置條件。 當條件評估為 $false時,迴圈For就會終止。

在下列範例中,迴圈會在 For 的值 $i 小於或等於 10 時執行。

$i=1
for(;$i -le 10;$i++)
{
    Write-Host $i
}

您可以使用 語句的 For Init 部分,在循環For執行這項工作,而不是在 語句外部For建立和初始化變數。

for($i=1; $i -le 10; $i++){Write-Host $i}

您可以使用歸位字元,而不是分號來分隔語句的 For InitConditionRepeat 部分。 下列範例示範 For 使用這個替代語法的 。

for ($i = 0
  $i -lt 10
  $i++){
  $i
}

此語句的 For 替代形式可在PowerShell腳本檔案和PowerShell命令提示字元中運作。 不過,當您在命令提示字元輸入互動式命令時,使用語句語法與分號比較容易 For

迴圈 ForForeach 迴圈更有彈性,因為它可讓您使用模式來遞增數位或集合中的值。 在下列範例中, $i 變數會在語句的 Repeat 部分中 For 遞增 2。

for ($i = 0; $i -le 20; $i += 2)
{
    Write-Host $i
}

迴圈 For 也可以寫入一行,如下列範例所示。

for ($i = 0; $i -lt 10; $i++) { Write-Host $i }

功能範例

下列範例示範如何使用迴圈逐一 For 查看檔案陣列,並重新命名它們。 資料夾中的 work_items 檔案具有其工作專案標識碼作為檔名。 迴圈會逐一查看檔案,以確保標識符編號以零填補為五位數。

首先,程式代碼會擷取工作專案數據檔的清單。 它們是使用其名稱格式 <work-item-type>-<work-item-number> 的所有 JSON 檔案。 使用儲存至變數的 $fileList 檔案信息物件,您可以依名稱排序它們,並查看當專案依類型分組時,依標識符排序專案的順序是非預期的。

$fileList = Get-ChildItem -Path ./work_items
$fileList | Sort-Object -Descending -Property Name
bug-219.json
bug-41.json
bug-500.json
bug-697.json
bug-819.json
bug-840.json
feat-176.json
feat-367.json
feat-373.json
feat-434.json
feat-676.json
feat-690.json
feat-880.json
feat-944.json
maint-103.json
maint-367.json
maint-454.json
maint-49.json
maint-562.json
maint-579.json

為了確保您可以英數位元排序工作專案,工作專案編號必須以零填補。

程序代碼會先搜尋具有最長數值後綴的工作專案,以執行此動作。 它會使用 for 迴圈迴圈來迴圈檔案,並使用索引來存取陣列中的每個檔案。 它會比較每個檔名與正則表達式模式,以將工作專案編號擷取為字元串,而不是整數。 然後,它會比較工作項目編號的長度,以尋找最長的數位。

# Default the longest numeral count to 1, since it can't be smaller.
$longestNumeralCount = 1

# Regular expression to find the numerals in the filename - use a template
# to simplify updating the pattern as needed.
$patternTemplate = '-(?<WorkItemNumber>{{{0},{1}}})\.json'
$pattern         =  $patternTemplate -f $longestNumeralCount

# Iterate, checking the length of the work item number as a string.
for (
    $i = 0                 # Start at zero for first array item.
    $i -lt $fileList.Count # Stop on the last item in the array.
    $i++                   # Increment by one to step through the array.
) {
    if ($fileList[$i].Name -match $pattern) {
        $numeralCount = $Matches.WorkItemNumber.Length
        if ($numeralCount -gt $longestNumeralCount) {
            # Count is higher, check against it for remaining items.
            $longestNumeralCount = $numeralCount
            # Update the pattern to speed up the search, ignoring items
            # with a smaller numeral count using pattern matching.
            $pattern = $patternTemplate -f $longestNumeralCount
        }
    }
}

既然您知道工作專案的最大數字計數,您可以迴圈查看檔案,視需要重新命名它們。 下一個代碼段會再次逐一查看檔案清單,並視需要填補它們。 它會使用另一個正則表達式模式,只處理數位計數小於最大值的檔案。

# Regular expression to find the numerals in the filename, but only if the
# numeral count is smaller than the longest numeral count.
$pattern = $patternTemplate -f 1, ($longestNumeralCount - 1)
for (
    $i = 0                 # Start at zero for first array item.
    $i -lt $fileList.Count # Stop on the last item in the array.
    $i++                   # Increment by one to step through the array.
) {
    # Get the file from the array to process
    $file = $fileList[$i]

    # If the file doesn't need to be renamed, continue to the next file
    if ($file.Name -notmatch $pattern) {
        continue
    }

    # Get the work item number from the regular expression, create the
    # padded string from it, and define the new filename by replacing
    # the original number string with the padded number string.
    $workItemNumber = $Matches.WorkItemNumber
    $paddedNumber   = "{0:d$longestNumeralCount}" -f $workItemNumber
    $paddedName     = $file.Name -replace $workItemNumber, $paddedNumber

    # Rename the file with the padded work item number.
    $file | Rename-Item -NewName $paddedName
}

現在檔案已重新命名,您可以再次擷取檔案清單,並依名稱排序舊檔案和新檔案。 下列代碼段會再次擷取檔案,以儲存在新的陣列中,並與初始物件集進行比較。 然後它會排序這兩個檔案陣列,並將已排序的陣列儲存到新的變數 $sortedOriginal$sortedPadded。 最後,它會使用 迴圈逐一 for 查看數位,並輸出具有下列屬性的物件:

  • Index 代表已排序陣列中的目前索引。
  • Original 是目前索引上原始檔名之排序陣列中的專案。
  • Padded 是目前索引上已填補檔名之已排序陣列中的專案。
$paddedList = Get-ChildItem -path ./work_items

# Sort both file lists by name.
$sortedOriginal = $fileList    | Sort-Object -Property Name
$sortedPadded   = $renamedList | Sort-Object -Property Name

# Iterate over the arrays and output an object to simplify comparing how
# the arrays were sorted before and after padding the work item numbers.
for (
  $i = 0
  $i -lt $fileList.Count
  $i++
) {
    [pscustomobject] @{
        Index    = $i
        Original = $sortedOriginal[$i].Name
        Padded   = $sortedPadded[$i].Name
    }
}
Index Original       Padded
----- --------       ------
    0 bug-219.json   bug-00041.json
    1 bug-41.json    bug-00219.json
    2 bug-500.json   bug-00500.json
    3 bug-697.json   bug-00697.json
    4 bug-819.json   bug-00819.json
    5 bug-840.json   bug-00840.json
    6 feat-176.json  feat-00176.json
    7 feat-367.json  feat-00367.json
    8 feat-373.json  feat-00373.json
    9 feat-434.json  feat-00434.json
   10 feat-676.json  feat-00676.json
   11 feat-690.json  feat-00690.json
   12 feat-880.json  feat-00880.json
   13 feat-944.json  feat-00944.json
   14 maint-103.json maint-00049.json
   15 maint-367.json maint-00103.json
   16 maint-454.json maint-00367.json
   17 maint-49.json  maint-00454.json
   18 maint-562.json maint-00562.json
   19 maint-579.json maint-00579.json

在輸出中,填補後的已排序工作專案會以預期的順序排列。

另請參閱