15

I want to select the second/third/forth object of a Get-ChildItem statement in my PowerShell script. This gives me the first:

$first = Get-ChildItem -Path $dir |
         Sort-Object CreationTime -Descending |
         Select-Object -First 1

This gives me the first three:

$latest = Get-ChildItem -Path $dir |
          Sort-Object CreationTime -Descending |
          Select-Object -First 3

I would like to get the second, or the third, or the fourth. (NOT the first two and so on).

Is there a way?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Tobi123
  • 508
  • 4
  • 8
  • 25

4 Answers4

27

For selecting the n-th element skip over the first n-1 elements:

$third = Get-ChildItem -Path $dir |
         Sort-Object CreationTime -Descending |
         Select-Object -Skip 2 |
         Select-Object -First 1

or select the first n and then of those the last element:

$third = Get-ChildItem -Path $dir |
         Sort-Object CreationTime -Descending |
         Select-Object -First 3 |
         Select-Object -Last 1

Beware, though, that the two approaches will yield different results if the input has less than n elements. The first approach would return $null in that scenario, whereas the second approach would return the last available element. Depending on your requirements you may need to choose one or the other.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
3

The second approach suggested by @AnsgarWiechers can easily be turned into a simple reusable funtion, like so:

function Select-Nth {
    param([int]$N) 

    $Input | Select-Object -First $N | Select-Object -Last 1
}

And then

PS C:\> 1,2,3,4,5 |Select-Nth 3
3
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
2

You could also access the element as an array item, using the index n-1. This seems more succinct than chaining pipes.

$third = (Get-ChildItem -Path $dir | Sort-Object CreationTime -Descending)[2]
theta-fish
  • 189
  • 1
  • 7
1

First Item

gci > out.txt
Get-Content out.txt | Select -Index 7 | Format-list

Second Item

gci > out.txt
Get-Content out.txt | Select -Index 8 | Format-list

The item between n and p

$n=3 
$p=7
$count = 0
$index = $n+7
$p=7+7
while($true){ 
   $index = $index + $count
   Get-Content out.txt | Select -Index $index | Format-list
   if($index -eq $p)
   {    
      break;
   }
   $count = $count + 1 
}

Note : The first seven lines are empty and the description lines.

MahmutKarali
  • 339
  • 4
  • 8