SoFunction
Updated on 2025-03-09

How PowerShell reads the content of a specified line in a text file

This article introduces how to get the Nth line of a text file in one step in a PowerShell. For example, a text file has 1000 lines. I want to directly extract the content of line 500. The easiest way is to implement it through PowerShell.

In PowerShell, you can use the Get-Content cmdlet to get the content of the text file. Get-Content reads a text file into an array, and each array element is a line of contents of the file. For example, the content of a text file is as follows:

Copy the codeThe code is as follows:

111
222
333

Then, use Get-Content to get an array, the array includes three elements, and the values ​​are: $a[0]="111", $a[1]="222", $a[2]="333".

Regarding the content of Get-Content reading text file, there is another parameter that needs to be mentioned, that is -totalcount, which means how many lines are obtained from the text file. For example: Get-Content d:\ -totalcount 10 means that 10 lines of content are read from d:\.

Okay, with the above two knowledge, let’s take a look at how to use Get-Content to get the Nth line of the file in PowerShell. For example, we want to get the second line in the above file, which is "222". The procedure is as follows:

Copy the codeThe code is as follows:

PS C:\Users\splaybow> (Get-Content d:\ -TotalCount 2)[-1]
222

Explain the above results:
1. We should be clear about the paragraph "Get-Content d:\ -TotalCount 2", which means that the first 2 lines are taken out from d:\.
2. Add brackets to the objects in the first two lines, and then take [-1], which means taking the last value of the array element. Because the previous one is read-only 2 lines, then the last value of the array composed of 2 lines is the value of the second line. Therefore, the function of obtaining the content of the N-line of the text file is realized.

This article introduces so much about PowerShell getting the Nth line of text file. I hope it will be helpful to you. Thank you!