PowerShell: How to Sort an Array of Strings by Date


Often you may want to sort an array of strings by date in PowerShell.

You can use the following basic syntax to do so:

[DateTime[]]$my_array = @('2024-10-15', '2024-10-22', '2024-08-25', ...)

$my_array | Sort-Object

This particular example sorts the strings in the array named $my_array based on date.

Note that when creating an array of dates, it’s recommended to use [DateTime[]] to ensure that the strings are recognized as dates.

The following example shows how to use this syntax in practice.

Example: How to Sort an Array of Strings by Date in PowerShell

Suppose that we create an array named $my_array that contains several strings that represent dates.

We can use the Sort-Object cmdlet with the following syntax to sort the array by date:

[DateTime[]]$my_array = @('2024-10-15', '2024-10-22', '2024-08-25', '2024-09-15', '2024-01-14')

$my_array | Sort-Object

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

PowerShell sort array of strings by date

Notice that this returns each of the dates in the array sorted from oldest to newest date.

If you would instead like to sort from newest to oldest date then you can add the -Descending operator at the end as follows:

[DateTime[]]$my_array = @('2024-10-15', '2024-10-22', '2024-08-25', '2024-09-15', '2024-01-14')

$my_array | Sort-Object -Descending

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

PowerShell sort by date descending

Notice that this returns each of the dates in the array sorted from newest to oldest date.

Note: You can find the complete documentation for the Sort-Object cmdlet in PowerShell here.

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