PowerShell: How to Use Select-Object and Skip Lines


Often you may want to use the Select-Object cmdlet in PowerShell and skip multiple lines.

You can use the following methods to do so:

Method 1: Use Select-Object and Skip First N Lines

Get-Content cities.txt | Select-Object -skip 3

This particular example returns all of the lines from the text file named cities.txt, but skips the first 3 lines in the file.

Method 2: Use Select-Object and Skip Specific Range of Lines

Get-Content cities.txt | ? {$_.readcount -lt 3 -or $_.readcount -gt 6}

This particular example returns all of the lines from the text file named cities.txt, but skips lines 3 through 6 in the file.

Note: The ? symbol is an alias for the Where-Object cmdlet, which is used to filter lines in an object.

The following examples show how to use each method in practice with the following file in our current directory named cities.txt:

Example 1: Use Select-Object and Skip First N Lines

We can use the following syntax to return all lines from the cities.txt file, but skip the first 3 lines:

Get-Content cities.txt | Select-Object -skip 3

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

PowerShell Select-Object skip lines

Notice that this returns all lines from the file except for the first 3 lines.

Example 2: Use Select-Object and Skip Specific Range of Lines

We can use the following syntax to return all lines from the cities.txt file, but skip lines 3 through 6 in the file:

Get-Content cities.txt | ? {$_.readcount -lt 3 -or $_.readcount -gt 6}

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

PowerShell Select-Object skip specific range of lines

Notice that this returns all lines from the file except for lines 3 through 6.

Note that the readcount property extracts the line number for each line in the file.

By using -lt (less than) and -gt (greater than) we are able to filter out lines that are less than or greater than specific line numbers.

Related Tutorials

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

PowerShell: How to Use Select-Object to Only Get Property Value
PowerShell: How to Use Select-Object and Rename Property
PowerShell: How to Use Group-Object with Multiple Properties
PowerShell: How to Use Sort-Object with Multiple Properties

Leave a Reply