在 Windows PowerShell 中如何逐行读取文件
- 
          
            在 PowerShell 中使用 Get-Content和ForEach循环逐行读取文件
- 
          
            在 PowerShell 中使用 Get-Content和Foreach-Object逐行读取文件
- 
          
            使用 [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
根据 Microsoft 的说法,正则表达式是用于匹配文本的模式。它可以由字面字符、运算符和其他结构组成。本文将尝试不同的脚本,涉及一个标准变量,称为正则表达式,表示为 $regex。
在 PowerShell 中使用 Get-Content 和 ForEach 循环逐行读取文件
我们最初讨论了 Get-Content cmdlet 在加载大文件时的缺陷,因为它会一次性将文件内容加载到内存中。但是,我们可以通过逐行加载来改进,使用 foreach 循环。
示例代码:
foreach ($line in Get-Content .\file.txt) {
    if ($line -match $regex) {
        Write-Output $line
    }
}
以下是该过程的逐步说明:
- 
获取文件内容: 我们首先使用 Get-Contentcmdlet 来读取文件的内容。Get-Content .\file.txt将 "file.txt"替换为您的文件路径。
- 
遍历每一行: 接下来,我们使用 ForEach循环遍历文件中的每一行。循环将每一行分配给一个变量$line,一次一行。在循环内部,您可以用根据您的要求处理每一行的代码替换 Write-Host $line。在本示例中,我们只是使用Write-Host显示每一行,但您可以执行任何所需的操作。
在 PowerShell 中使用 Get-Content 和 Foreach-Object 逐行读取文件
要在 PowerShell 中使用 Get-Content 和 Foreach-Object 逐行读取文件,请遵循以下步骤:
- 
使用 Get-ContentCmdlet:我们首先使用 Get-Contentcmdlet 来读取文件的内容。Get-Contentcmdlet 逐行读取文件并将其作为对象输出到管道中。powershellCopy codeGet-Content -Path "example.txt" | ForEach-Object { # Process each line here $_ # $_ represents the current line }
将 "example.txt" 替换为您的文件路径。
- 
Foreach-Object 循环: 接下来,我们使用 Foreach-Objectcmdlet(%是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-Pathcmdlet 检查文件是否存在。
- 如果文件存在,我们使用 Get-Content读取其内容并传递给Foreach-Object进行处理。
- 在 Foreach-Object脚本块中,我们使用Write-Host $_显示每一行。
使用 [System.IO.File] 类在 PowerShell 中逐行读取文件
要在 PowerShell 中使用 [System.IO.File] 类逐行读取文件,请遵循以下步骤:
- 
指定文件路径: 首先,指定要读取的文件的路径。将 "example.txt"替换为您的实际文件路径。powershellCopy code $filePath = "example.txt"
- 
检查文件是否存在: 在尝试读取文件之前,使用 Test-Pathcmdlet 检查文件是否存在是一种良好的实践: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-Pathcmdlet 检查文件是否存在是一种良好的实践: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