如何在 Windows PowerShell 中逐行讀取文件
-
使用
Get-Content
和ForEach
循環逐行讀取 PowerShell 中的文件 -
使用
Get-Content
和Foreach-Object
逐行讀取 PowerShell 中的文件 -
使用
[System.IO.File]
類在 PowerShell 中逐行讀取文件 -
使用
System.IO.StreamReader
類在 PowerShell 中逐行讀取文件 - 總結

在 Windows PowerShell 中,我們可以使用 Get-Content
Cmdlet 從文件中讀取內容。然而,該 Cmdlet 會一次性將整個文件內容加載到內存中,這在處理大型文件時會失敗或凍結。
為了解決這個問題,我們可以逐行讀取文件,本文將向您展示如何做。
在開始之前,最好是創建一個包含多行的示例文本文件。例如,我創建了一個包含以下行的 file.txt
。
file.txt
:
one
two
three
four
five
six
seven
eight
nine
ten
根據微軟的說法,正則表達式是一種用於匹配文本的模式。它可以由字面字符、運算符和其他結構組成。本文將嘗試不同的腳本,涉及一個名為正則表達式的標準變量,用 $regex
表示。
使用 Get-Content
和 ForEach
循環逐行讀取 PowerShell 中的文件
我們最初已經討論了 Get-Content
Cmdlet 在讀取大型文件時的缺陷,因為它會一次性將文件的內容加載到內存中。然而,我們可以通過使用 foreach
循環逐行加載來改進它。
示例代碼:
foreach ($line in Get-Content .\file.txt) {
if ($line -match $regex) {
Write-Output $line
}
}
以下是該過程的逐步說明:
-
獲取文件內容:
我們首先使用
Get-Content
Cmdlet 來讀取文件的內容。Get-Content .\file.txt
將
"file.txt"
替換為您的文件路徑。 -
遍歷每一行:
接下來,我們使用
ForEach
循環遍歷文件中的每一行。循環將每一行依次分配給變量$line
。在循環內,您可以根據您的要求將
Write-Host $line
替換為處理每一行的代碼。在這個示例中,我們僅用Write-Host
顯示每一行,但您可以執行任何所需的操作。
使用 Get-Content
和 Foreach-Object
逐行讀取 PowerShell 中的文件
要在 PowerShell 中使用 Get-Content
和 Foreach-Object
逐行讀取文件,請遵循以下步驟:
-
使用
Get-Content
Cmdlet:我們首先使用
Get-Content
Cmdlet 來讀取文件的內容。Get-Content
Cmdlet 讀取文件的每一行並將其輸出為管道中的對象。powershellCopy codeGet-Content -Path "example.txt" | ForEach-Object { # Process each line here $_ # $_ represents the current line }
將 "example.txt"
替換為您的文件路徑。
-
Foreach-Object 循環:
接下來,我們使用
Foreach-Object
Cmdlet(%
是Foreach-Object
的別名)來遍歷管道中的每一行。在腳本塊({}
內的代碼)中,您可以使用$_
來處理當前正在處理的行。powershellCopy codeGet-Content -Path "example.txt" | ForEach-Object { # Process each line here $_ # $_ represents the current line }
在這個循環中,您可以對每一行執行所需的操作。
完整的工作代碼示例
這裡是一個完整的工作代碼示例,它逐行讀取文件並顯示每一行:
powershellCopy code# Specify the path to the file
$filePath = "example.txt"
# Check if the file exists
if (Test-Path $filePath) {
# Read the file line by line and process each line
Get-Content -Path $filePath | ForEach-Object {
# Process each line here
Write-Host $_
}
} else {
Write-Host "File not found: $filePath"
}
在這段代碼中:
- 我們使用
$filePath
變量指定文件的路徑。 - 我們使用
Test-Path
Cmdlet 來檢查文件是否存在。 - 如果文件存在,我們使用
Get-Content
來讀取其內容並將其傳遞給Foreach-Object
進行處理。 - 在
Foreach-Object
腳本塊內,我們使用Write-Host $_
來顯示每一行。
使用 [System.IO.File]
類在 PowerShell 中逐行讀取文件
要在 PowerShell 中使用 [System.IO.File]
類逐行讀取文件,請遵循以下步驟:
-
指定文件路徑:
首先指定要讀取的文件的路徑。將
"example.txt"
替換為您的文件的實際路徑。powershellCopy code $filePath = "example.txt"
-
檢查文件是否存在:
在嘗試讀取文件之前,最好使用
Test-Path
Cmdlet 檢查文件是否存在:powershellCopy codeif (Test-Path $filePath) { # File exists, proceed with reading } else { Write-Host "File not found: $filePath" }
-
逐行讀取文件:
確認文件存在後,您可以使用
[System.IO.File]
類逐行讀取文件。以下是實現此操作的代碼:powershellCopy codetry { $lines = [System.IO.File]::ReadLines($filePath) foreach ($line in $lines) { # Process each line here Write-Host $line } } catch { Write-Host "Error reading the file: $_" }
在這段代碼中:
- 我們使用
[System.IO.File]
類的ReadLines
方法逐行讀取文件,並將行存儲在$lines
變量中。 - 然後我們使用
foreach
循環遍歷$lines
中的每一行並進行處理。在這個示例中,我們僅使用Write-Host
顯示每一行,但您可以執行任何所需的操作。
- 我們使用
完整的工作代碼示例
這裡是一個完整的工作代碼示例,它逐行讀取文件並顯示每一行:
powershellCopy code# Specify the path to the file
$filePath = "example.txt"
# Check if the file exists
if (Test-Path $filePath) {
try {
# Read the file line by line
$lines = [System.IO.File]::ReadLines($filePath)
foreach ($line in $lines) {
# Process each line here
Write-Host $line
}
} catch {
Write-Host "Error reading the file: $_"
}
} else {
Write-Host "File not found: $filePath"
}
在這段代碼中:
- 我們使用
$filePath
變量指定文件的路徑。 - 我們使用
Test-Path
檢查文件是否存在。 - 如果文件存在,我們使用
[System.IO.File]::ReadLines()
方法逐行讀取文件並使用foreach
循環處理每一行。 - 我們包括了錯誤處理來捕捉在讀取文件時可能發生的任何異常。
使用 System.IO.StreamReader
類在 PowerShell 中逐行讀取文件
要在 PowerShell 中使用 System.IO.StreamReader
類逐行讀取文件,請遵循以下步驟:
-
指定文件路徑:
首先指定要讀取的文件的路徑。將
"example.txt"
替換為您的文件的實際路徑。powershellCopy code $filePath = "example.txt"
-
檢查文件是否存在:
在嘗試讀取文件之前,最好使用
Test-Path
Cmdlet 檢查文件是否存在:powershellCopy codeif (Test-Path $filePath) { # File exists, proceed with reading } else { Write-Host "File not found: $filePath" }
-
逐行讀取文件:
確認文件存在後,您可以使用
System.IO.StreamReader
類逐行讀取文件。以下是實現此操作的代碼:
powershellCopy codetry {
$reader = [System.IO.StreamReader]::new($filePath)
while ($reader.Peek() -ge 0) {
$line = $reader.ReadLine()
# Process each line here
Write-Host $line
}
$reader.Close()
} catch {
Write-Host "Error reading the file: $_"
}
在這段代碼中:
- 我們使用
[System.IO.StreamReader]::new($filePath)
創建System.IO.StreamReader
的一個新實例,其中$filePath
是文件的路徑。 - 我們使用
while
循環逐行讀取文件。$reader.Peek() -ge 0
條件確保我們會繼續讀取直到文件結尾。 - 在循環內,我們使用
$reader.ReadLine()
讀取每一行並根據需要進行處理。在這個示例中,我們僅使用Write-Host
顯示每一行,但您可以執行任何所需的操作。 - 最後,我們使用
$reader.Close()
關閉StreamReader
以釋放文件資源。
完整的工作代碼示例
這裡是一個完整的工作代碼示例,它逐行讀取文件並顯示每一行:
powershellCopy code# Specify the path to the file
$filePath = "example.txt"
# Check if the file exists
if (Test-Path $filePath) {
try {
# Create a StreamReader to read the file
$reader = [System.IO.StreamReader]::new($filePath)
# Read the file line by line
while ($reader.Peek() -ge 0) {
$line = $reader.ReadLine()
# Process each line here
Write-Host $line
}
# Close the StreamReader
$reader.Close()
} catch {
Write-Host "Error reading the file: $_"
}
} else {
Write-Host "File not found: $filePath"
}
在這段代碼中:
- 我們使用
$filePath
變量指定文件的路徑。 - 我們使用
Test-Path
檢查文件是否存在。 - 如果文件存在,我們創建一個
System.IO.StreamReader
實例來逐行讀取文件並使用while
循環處理每一行。 - 我們包括了錯誤處理來捕捉在讀取文件時可能發生的任何異常。
總結
總的來說,PowerShell 提供了幾種多功能的方法來逐行讀取文件,以滿足多樣化的腳本和自動化需求。使用 Get-Content
和 ForEach
循環是用於簡單任務的用戶友好選擇,提供了簡單性和可讀性。使用 Get-Content
和 Foreach-Object
增強了靈活性,使其適合在管道中進行更複雜的操作和篩選任務。
對於需要更大控制和全面錯誤處理的情況,[System.IO.File]
類提供了一個強大的解決方案。這種方法允許您微調文件操作並妥善處理異常,使其適合於穩定且抗錯誤的腳本。
在處理大型文件且內存效率至關重要的情況下,System.IO.StreamReader
類表現出色。它允許您有效地讀取文件,同時更有效地管理內存資源,確保對大量數據集的順暢處理。
最終,方法的選擇取決於您的具體腳本需求、文件大小和處理的複雜性。通過利用這些方法,您可以自信地在 PowerShell 中逐行讀取文件,有效地處理自動化工作流中的各種文件相關任務。
Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
LinkedIn