PowerShell: How to Select Second Object in Output


Often you may want to only select the second object from the output in PowerShell.

You can use the following syntax to do so:

Get-ChildItem |
Select-Object -Skip 1 |
Select-Object -First 1

This particular example will return only the second object in the output.

Here is what the various commands do:

  • Get-ChildItem: Retrieve all items in the current directory
  • Select-Object -Skip 1: Return all items except for the first item in the output
  • Select-Object -First 1: Of the remaining items, return only the first item in the output

Note that this particular example returns the second object in the output, but you only need to change the value after the -Skip parameter to select a different nth object in the output.

For example, you can use -Skip 2 to instead select the third object.

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

Example: How to Select Second Object in Output in PowerShell

Suppose we use the Get-ChildItem cmdlet to first view all of the items in our current directory:

We can see that our current directory has five total files:

  • nba_data.csv
  • sales_data.csv
  • teams1.txt
  • teams2.txt
  • teams3.txt

Suppose that we would like to return only the second file from this list, which is the file named sales_data.csv.

We can use the following syntax to do so:

Get-ChildItem |
Select-Object -Skip 1 |
Select-Object -First 1

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

PowerShell select second object in output

Notice that this only returns sales_data.csv, which was the second file shown in the original output.

Note that you could also use -Skip 2 to instead return the third file from the original output:

Get-ChildItem |
Select-Object -Skip 2 |
Select-Object -First 1

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

PowerShell select third object in output

Notice that this only returns teams1.txt, which was the third file shown in the original output.

Feel free to replace the value after the -Skip parameter to select any nth object you’d like from the output.

Related Tutorials

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

PowerShell: How to Get First File that Matches a Pattern
PowerShell: How to Get First Filename from a Folder
PowerShell: How to Get File Name from Path

Leave a Reply