Sort With PS Code

by Apr 30, 2009

Sort-Object is a great and versatile cmdlet to sort anything you want. Simply specify the property or properties you want to use for sorting:

Dir Length
Dir Name

A little known fact is that Sort-Object also accepts script blocks to sort different criteria. For example, the next line sorts your directory listing by length of name:

Dir | Sort-Object {$_.Name.Length} -descending

Within the curly brackets, $_ represents the objects returned by Dir. As such, Sort-Object uses the result of your script block for sorting.