PowerShell: How to Get the Last N Lines of a File


Often you may want to use PowerShell to get the last N lines of a file.

The easiest way to do so is by using the Get-Content cmdlet with the -Tail parameter:

Get-Content players.txt -Tail 4

This particular example gets the last 4 lines of the text file named players.txt.

Note that -Last is an alias of the -Tail parameter and will also extract the last N lines of a file:

Get-Content players.txt -Last 4 

The following example shows how to use this syntax in practice to get the last N lines of a file.

Example: How to Get Last N Lines of 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 view the contents of this file:

Now suppose that we would like to only get the last 4 lines of the file.

We can use the following syntax to do so:

Get-Content players.txt -Tail 4

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

PowerShell get last N lines of file

Notice that this returns only the last 4 lines of the file.

Also note that we could use the -Last parameter instead to get the same results:

Get-Content players.txt -Last 4

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

PowerShell use last parameter in Get-Content

Notice that this also returns the last 4 lines of the file.

Note: You can find the complete documentation for the Get-Content cmdlet in PowerShell here.

Related Tutorials

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

PowerShell: How to Get Last Item in Array
PowerShell: How to List Files in Directory by Date
PowerShell: How to List All Files in Directory to Text File

Leave a Reply