PowerShell: How to Sort Version Strings


Often you may want to sort version strings in PowerShell.

You can use the following methods to do so:

Method 1: Sort Version Strings and Display Output as Strings

$version_strings | Sort-Object { $_ -as [Version] }

This particular example sorts the version strings stored in the array named $version_strings and displays the output as an array of strings.

Method 2: Sort Version Strings and Display Output as Table

$version_strings | ForEach-Object { [Version]$_ } | Sort-Object

This particular example sorts the version strings stored in the array named $version_strings and displays the output as a table that labels the Major, Minor, Build and Revision values of each version string.

The following examples show how to use each of these methods in practice.

Example 1: Sort Version Strings and Display Output as Strings

Suppose that we have the following version strings that we would like to sort:

  • 1.1.0.3
  • 1.7.0.0
  • 1.11.3.1
  • 0.2.1.1

We can use the following syntax to do so:

$version_strings = '1.1.0.3', '1.7.0.0', '1.11.3.1', '0.2.1.1'
$version_strings | Sort-Object { $_ -as [Version] }

The following screenshot shows how to use this syntax in practice:

PowerShell sort version strings

Notice that the output displays the versions strings sorted from smallest to largest.

Example 2: Sort Version Strings and Display Output as Table

Once again, suppose that we have the following version strings that we would like to sort:

  • 1.1.0.3
  • 1.7.0.0
  • 1.11.3.1
  • 0.2.1.1

We can use the following syntax to do so:

$version_strings = '1.1.0.3', '1.7.0.0', '1.11.3.1', '0.2.1.1'
$version_strings | ForEach-Object { [Version]$_ } | Sort-Object

The following screenshot shows how to use this syntax in practice:

PowerShell sort versions and display output as table

Notice that the output displays the versions strings sorted from smallest to largest, formatted in a table with labels for the Major, Minor, Build and Revision numbers.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Sort a Table with Format-Table
PowerShell: How to Sort by Specific Column
PowerShell: How to Use Sort-Object with Multiple Properties

Leave a Reply