Skip to content
AgileLogics
5 min read

Selecting and Sorting

Prerequisites: Filtering with Where-Object

Select-Object

Select-Object picks properties (columns) or a number of objects (rows):

$people = @(
  [pscustomobject]@{ Name = 'Ada';   City = 'London';   Age = 36; Email = 'ada@example.com' }
  [pscustomobject]@{ Name = 'Linus'; City = 'Helsinki'; Age = 28; Email = 'linus@example.com' }
  [pscustomobject]@{ Name = 'Grace'; City = 'New York'; Age = 45; Email = 'grace@example.com' }
)

$people | Select-Object Name, City
$people | Select-Object -First 1 -ExpandProperty Email

Name  City
----  ----
Ada   London
Linus Helsinki
Grace New York
ada@example.com
  • A list of names keeps those properties.
  • -First / -Last / -Skip pick objects.
  • -ExpandProperty outputs just the value of one property — plain strings instead of objects with a single column.

Calculated properties

Add a new property with a hash table of Name and Expression:

$people = @(
  [pscustomobject]@{ Name = 'Ada';   Age = 36 }
  [pscustomobject]@{ Name = 'Linus'; Age = 28 }
)

$people | Select-Object Name, @{ Name = 'AgeInMonths'; Expression = { $_.Age * 12 } }

Name  AgeInMonths
----  -----------
Ada           432
Linus         336

Sort-Object

$people = @(
  [pscustomobject]@{ Name = 'Ada';   City = 'London';   Age = 36 }
  [pscustomobject]@{ Name = 'Linus'; City = 'Helsinki'; Age = 28 }
  [pscustomobject]@{ Name = 'Grace'; City = 'New York'; Age = 45 }
  [pscustomobject]@{ Name = 'Alan';  City = 'London';   Age = 41 }
)

$people | Sort-Object Age -Descending | Select-Object Name, Age
$people | Sort-Object City, Name | ForEach-Object { "$($_.City): $($_.Name)" }
'b', 'a', 'c', 'a' | Sort-Object -Unique

Name  Age
----  ---
Grace  45
Alan   41
Ada    36
Linus  28
Helsinki: Linus
London: Ada
London: Alan
New York: Grace
a
b
c

Sort by several properties by listing them; -Unique removes duplicates.

Common mistakes

  • Using Select-Object to pick properties and then wondering why the result has extra formatting — that's normal: Select-Object returns new objects with only those properties.
  • Sorting text that holds numbers: '10', '9' sorts as text ('10' first). Convert to numbers first, or sort on a numeric property.