Displaying First Or Last Elements

by Apr 29, 2009

Select-Object can limit results to only the first or last elements. Simply use -first or -last:

dir | select-object -first 10
Get-Process | Sort-Object cpu -descending |
Select-Object -first 10
Get-Process | Sort-Object cpu -descending |
Select-Object -first 10 |
Format-Table name, CPU

You should note how Select-Object outputs internally only the first or last elements of the resulting array. You can get the same functionality by accessing array elements manually:

$a = Get-Process | Sort-Object cpu -descending
$a[0..9]
$a[1..10]

Also, Select-Object will not terminate the pipeline once it has retrieved the given number of elements. Instead, it works like a filter and returns only the elements you requested, but has no effect on the previous pipeline command.