PowerShell: Use Get-Content and Skip First N Lines


Often you may want to use the Get-Content cmdlet in PowerShell to read the contents of a file but skip the first N lines.

You can use the following syntax to do so:

Get-Content $my_file | Select-Object -Skip 3

This particular example will read all of the lines from the file located at the path we specified in $my_file but skip the first 3 lines.

Note: Feel free to replace 3 with whatever number you would like after the -Skip operator to instead skip a different number of lines at the beginning of the file.

The following example shows how to use this syntax in practice.

Example: Use Get-Content and Skip First N Lines in PowerShell

Suppose we have a file named teams.txt that contains ten total lines with the names of various basketball teams.

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

Suppose that we would like to read all of the lines of this file but skip the first 3 lines.

We can use the following syntax to do so:

$my_file = "c:\users\bobbi\teams.txt"
Get-Content $my_file | Select-Object -Skip 3

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

PowerShell get-content skip first n lines

Notice that we are able to read all of the lines in the file but skip the first 3 lines.

Note that if you would instead like to skip the last 3 lines then you could use the -SkipLast operator instead:

$my_file = "c:\users\bobbi\teams.txt"
Get-Content $my_file | Select-Object -SkipLast 3

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

PowerShell get-content skip last n lines in file

Notice that we are able to read all of the lines in the file but skip the last 3 lines.

Note: The -SkipLast operator is only available for PowerShell versions 5.0 or higher.

Related Tutorials

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

PowerShell: How to Get First Line of File
PowerShell: How to Get First Item in Array
PowerShell: How to Get First Character of String

Leave a Reply