Select the second or third object / element

I want to select the second / third / fourth operator object Get-ChildItem

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 a second, or a third, or a fourth. (NOT the first two, etc.).

Is there a way?

+3


source to share


3 answers


To select the nth element, skip 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 the last item:



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

Beware, however, that the two approaches will yield different results if the input has fewer than n elements. The first approach will return $null

in this scenario, whereas the second approach will return the last available item. Depending on your requirements, you may need to choose one or the other.

+6


source


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

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

      

+1


source


First element

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

      

Second element

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

      

Element 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 blank and description lines.

0


source







All Articles