Reading Specific Lines from a Text File

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Posts: 12
Joined: Fri Nov 09, 2018 1:20 pm

Reading Specific Lines from a Text File

Post by azeiler »

Is there a very efficient way to read specific lines from a text file? Say I wanted to read lines 54 through 78 of a text file, what would the most efficient way to do that be?

Get-Content seems to be extremely inefficient with large files. Elsewhere I've seen suggestions like:

Get-Content "file.txt" | Select-Object -Index (54..78)

Correct me if I'm wrong, but isn't this method simply reading the entire file first, and then filtering all the content? So that wouldn't be any more efficient then using Get-Content by itself and then using Indexing to grab the lines you want.

Currently I am able to use a Select-String operation to determine *which* lines to bring in. Now I would like to know if there's an easy way to say "read ONLY these certain lines and save them to a variable."

Posts: 14458
Joined: Tue May 22, 2007 9:57 am

Re: Reading Specific Lines from a Text File

Post by jvierra »

That reads the whole file. With text files we have no options of selecting a line. We can only read the file and detect lines. You must read the whole file then find the lines. You can try the following as it may be slightly faster especially for the lines at the beginning of the file.

Get-Content <file> -TotalCount 78 | select -skip 53