PowerShell: How to Print Specific Line in File


You can use the following syntax in PowerShell to print only line number 6 of a specific file:

Get-Content players.txt | Select-Object -Index 5

This particular example will print only line number 6 from the file named players.txt.

Note that the first line in a file has index position 0, which is why we used -Index 5 to retrieve line number 6.

This method uses the Get-Content cmdlet to first read all lines of a given file, which could be inefficient if the file is extremely large.

If you’re working with a large file, a more efficient approach would be to use the -TotalCount parameter to only read the first n lines of a file and then print only the nth line:

Get-Content players.txt -TotalCount 6 | Select-Object -Last 1

This method will also print only line number 6 from the filed named players.txt.

The following examples show how to use each of these methods in practice.

Example: How to Print Specific Line in File Using PowerShell

Suppose we have a file named players.txt that contains information about various basketball players.

We can use the Get-Content cmdlet to first view all lines in this file:

Now suppose that we only want to print line number 6 of the file.

We can use the following syntax to do so:

Get-Content players.txt | Select-Object -Index 5

The following screenshot shows how to use this syntax in practice:

PowerShell print specific line in file

Notice that this prints only line number 6 of the file.

If we were concerned about performance due to a large file, we could use the following syntax instead:

Get-Content players.txt -TotalCount 6 | Select-Object -Last 1

The following screenshot shows how to use this syntax in practice:

PowerShell print specific line of large file

Notice that this also prints only line number 6 of the file.

Feel free to use whichever method you prefer depending on the size of your file.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to List Files in Directory by Date
PowerShell: How to List All Files in Directory to Text File
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply