04 December 2007

PowerShell Directories, Collection and Range Operator

What are the biggest files in a directory? Using the Select-Object Cmdlet provides this command chain:

Get-ChildItem c:\windows\*.* | Sort-Object length -descending | Select-Object -first 3

In the article, the first two commands produce a collection and Select-Object picks the first three items. It's a little tedious having long command chains, so can we make it shorter? Since we have a collection, we can access its items using the array syntax and an index:

(Get-ChildItem c:\windows\*.* | Sort-Object length -descending)[3]

Using the dot-dot range operator (..), we can generate a list of indices using [0..2] (collections start with a 0 index) and reproduce the effect of Select-Object -first 3:

(Get-ChildItem c:\windows\*.* | Sort-Object length -descending)[0..2]

What about getting last 3 items using Select-Object -last 3? It can be replaced by [-3..-1]. Note that the last item in a collection starts from -1.

(Get-ChildItem c:\windows\*.* | Sort-Object length -descending)[-3..-1]