By Patrick Wahlmueller

AI and Automation in Practice

Technical Insights 1 min read

Sort String as Int

A simple PowerShell trick to sort strings numerically using -as [int] – essential when dealing with version numbers or ID strings.

Twice a year I need to sort a string as an integer. With PowerShell it’s really simple.

Without casting, Sort-Object sorts lexicographically – so "199" comes before "23":

"199", "23", "89" | Sort-Object
# Output: 199, 23, 89  (wrong order)

The fix is to cast to [int] inside a script block:

"199", "23", "89" | Sort-Object -Property { $_ -as [int] }
# Output: 23, 89, 199  (correct order)

This tip comes from Mathias R. Jessen. He also covers more advanced cases – for example sorting mixed strings like IR343 and IR1342 numerically – in his RegEx session at PSConfEU.