共用方式為


about_Foreach

簡短描述

描述可用來周遊專案集合中所有項目的語言命令。

完整描述

foreach 語句是一種語言建構,用於逐一查看集合中的一組值。

要周遊的最簡單且最典型的集合類型是陣列。 在 foreach 迴圈中,通常會對數位列中的每個項目執行一或多個命令。

語法

下列顯示 foreach 語法:

foreach ($<item> in $<collection>){<statement list>}

括弧內的 foreach 語句部分代表要反覆運算的變數和集合。 PowerShell 會在 $<item> 循環執行時自動建立變數 foreach。 在每個反覆項目開始時,foreach 將專案變數設定為集合中的下一個值。 {<statement list>} 區塊包含針對每個反覆專案執行的命令。

例子

例如,下列範例中的 foreach 循環會顯示 $letterArray 陣列中的值。

$letterArray = 'a','b','c','d'
foreach ($letter in $letterArray)
{
  Write-Host $letter
}

在這裡範例中,$letterArray 包含字串值 abcd。 第一次執行 foreach 語句時,它會將 $letter 變數設定為等於 $letterArray 中第一個專案 (a)。 然後,它會使用 Write-Host 來顯示值。 下次透過 循環時,$letter 會設定為 b。 此模式會針對數位中的每個項目重複。

您也可以搭配傳回專案集合的 Cmdlet 使用 foreach 語句。 在下列範例中,foreach 語句會逐步執行 Get-ChildItem Cmdlet 所傳回的項目清單。

foreach ($file in Get-ChildItem)
{
  Write-Host $file
}

您可以使用 if 語句來精簡範例,以限制傳回的結果。 在下列範例中,if 語句會將結果限製為大於 100 KB 的檔案(KB):

foreach ($file in Get-ChildItem)
{
  if ($file.Length -gt 100KB)
  {
    Write-Host $file
  }
}

在此範例中,foreach 迴圈會使用 $file 變數的 屬性來執行比較作業 ($file.Length -gt 100KB)。 $file 變數具有 由 Get-ChildItem傳回之物件的所有屬性。

在下一個範例中,腳本會顯示語句清單內的長度和上次存取時間:

foreach ($file in Get-ChildItem)
{
  if ($file.Length -gt 100KB)
  {
    Write-Host $file
    Write-Host $file.Length
    Write-Host $file.LastAccessTime
  }
}

您也可以使用來自 foreach 循環外部的變數。 下列範例會計算大小超過 100 KB 的檔案:

$i = 0
foreach ($file in Get-ChildItem) {
  if ($file.Length -gt 100KB) {
    Write-Host $file 'file size:' ($file.Length / 1024).ToString('F0') KB
    $i = $i + 1
  }
}

if ($i -ne 0) {
  Write-Host
  Write-Host $i ' file(s) over 100KB in the current directory.'
}
else {
  Write-Host 'No files greater than 100KB in the current directory.'
}

在上述範例中,$i 以 迴圈外部 0 的值開頭。 然後,每個大於 100KB 的檔案,$i 會在 循環內遞增。 循環結束時,if 語句會評估 $i 的值,以顯示超過100KB的檔案計數。

上述範例也會示範如何格式化檔案長度結果:

($file.Length / 1024).ToString('F0')

此值會除以 1,024 以顯示以 KB 而非位元組為單位的結果,然後產生的值會使用固定點格式規範來格式化,以從結果中移除任何十進位值。 0 會讓格式規範顯示沒有小數字數。

下列函式會剖析 PowerShell 腳本和腳本模組,並傳回所包含的函式位置。 範例展示了如何在陳述句區塊中使用MoveNext該方法及其Current變數foreach的特性$foreach

如需詳細資訊,請參閱使用列舉值

function Get-FunctionPosition {
  [CmdletBinding()]
  [OutputType('FunctionPosition')]
  param(
    [Parameter(Position = 0, Mandatory,
      ValueFromPipeline, ValueFromPipelineByPropertyName)]
    [ValidateNotNullOrEmpty()]
    [Alias('PSPath')]
    [System.String[]]
    $Path
  )

  process {
    try {
      $filesToProcess = if ($_ -is [System.IO.FileSystemInfo]) {
        $_
      } else {
        Get-Item -Path $Path
      }
      $parser = [System.Management.Automation.Language.Parser]
      foreach ($item in $filesToProcess) {
        if ($item.PSIsContainer -or
            $item.Extension -notin @('.ps1', '.psm1')) {
          continue
        }
        $tokens = $errors = $null
        $ast = $parser::ParseFile($item.FullName, ([ref]$tokens),
          ([ref]$errors))
        if ($errors) {
          $msg = "File '{0}' has {1} parser errors." -f $item.FullName,
            $errors.Count
          Write-Warning $msg
        }
        :tokenLoop foreach ($token in $tokens) {
          if ($token.Kind -ne 'Function') {
            continue
          }
          $position = $token.Extent.StartLineNumber
          do {
            if (-not $foreach.MoveNext()) {
              break tokenLoop
            }
            $token = $foreach.Current
          } until ($token.Kind -in @('Generic', 'Identifier'))
          $functionPosition = [pscustomobject]@{
            Name       = $token.Text
            LineNumber = $position
            Path       = $item.FullName
          }
          $addMemberSplat = @{
              InputObject = $functionPosition
              TypeName = 'FunctionPosition'
              PassThru = $true
          }
          Add-Member @addMemberSplat
        }
      }
    }
    catch {
      throw
    }
  }
}

另請參閱