Read Files Line by Line in Windows PowerShell

Marion Paul Kenneth Mendoza Jan 30, 2023 Dec 23, 2021
  1. Improving the Get-Content Cmdlet Syntax
  2. Loading Specific Lines Using switch
  3. Using the [System.IO.File] Class in PowerShell to Read File Line by Line
Read Files Line by Line in Windows PowerShell

In Windows PowerShell, we can use the Get-Content cmdlet to read files from a file. However, the cmdlet will load the entire file contents to memory at once, which will fail or freeze on large files.

To solve this problem, what we can do is we can read the files line by line, and this article will show you how.

Before we start, it is better if we create a sample text file with multiple lines. For example, I have created a file.txt containing the following lines.

file.txt:

one
two
three
four
five
six
seven
eight
nine
ten

According to Microsoft, a regular expression is a pattern used to match the text. It can be made up of literal characters, operators, and other constructs. This article will try different scripts involving a standard variable called Regular Expressions, denoted by $regex.

Improving the Get-Content Cmdlet Syntax

We have initially discussed that the Get-Content cmdlet has its flaws when we are loading a large file as it will load the contents of the file into memory all at once. However, we can improve it by loading the lines one by one using the foreach loop.

Example Code:

foreach($line in Get-Content .\file.txt) {
    if($line -match $regex){
        Write-Output $line
    }
}

Loading Specific Lines Using switch

We can use the $regex variable to input specific lines in our file by creating a custom $regex value and matching it in a switch case function.

Example Code:

$regex = '^t'

switch -regex -file file.txt {
  $regex { "line is $_" } 
}

Output:

line is two
line is three
line is ten

In this example, we have defined a custom value of $regex that will only match and display lines if it starts with the character t.

Using the [System.IO.File] Class in PowerShell to Read File Line by Line

If you have access to the .NET library, you could use the [System.IO.File] class to read contents from your file. It is a great alternative to Get-Content as you will not need regular expressions to handle files line by line.

Example Code:

foreach($line in [System.IO.File]::ReadLines("C:\yourpathhere\file.txt"))
{
    Write-Output $line
}
Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn

Related Article - PowerShell File