Friday, March 16, 2018

Sorting by expressions in PowerShell

PowerShell's sort cmdlet can order items by a given property. Sometimes it may be helpful to order based on some expression in terms of each item that doesn't appear as a property on the objects. To do that, you can use custom properties. The syntax is a little tricky. Instead of a property name, supply @{e={ expression }}, where expression can use $_ to access the item under consideration. For example, this sorts $someStrings by the strings' second character:

$someString | sort @{e={ $_[1] }}

No comments:

Post a Comment