Как сортировать массив по алфавиту в power shell


Often you may want to import data files into PowerShell and then sort the rows based on a specific column.

Method 1: Sort by String Column

This particular example imports the file specified at the path in the $my_file object, then sorts the rows in ascending order (A to Z) based on the values in the team column.

Note: By default, the Sort-Object cmdlet sorts values in ascending order. To instead sort by values in descending order, simply add the -descending operator at the end of the line.

Method 2: Sort by Numeric Column

This particular example imports the file specified at the path in the $my_file object, then sorts the rows in ascending order (smallest to largest) based on the values in the points column.

Example 1: How to Sort by String Column in PowerShell

Suppose we use the Import-Csv cmdlet to view the contents of this entire file:

Как сортировать массив по алфавиту в power shell

The file contains three columns that show the team, points and assists for various basketball players.

Suppose that we would like to sort the rows by the strings in the team column.

PowerShell sort by string column in ascending order

Notice that the rows are now sorted in order from A to Z based on the strings in the team column.

If you would instead like to sort from Z to A, simply add the -descending operator at the end of the line:

PowerShell sort by string column in descending order

Notice that the rows are now sorted in order from Z to A based on the strings in the team column.

Example 2: How to Sort by Numeric Column in PowerShell

Suppose we use the Import-Csv cmdlet to view the contents of this entire file:

Как сортировать массив по алфавиту в power shell

Suppose that we would like to sort the rows by the numeric values in the points column.

PowerShell sort by numeric column in ascending order

Notice that the rows are sorted in ascending order (smallest to largest) based on the value in the points column.

To instead sort the rows by the values in the points column in descending order (largest to smallest), simply add the -descending operator:

PowerShell sort by numeric column in descending order

Notice that the rows are now sorted in descending order (largest to smallest) based on the value in the points column.

PowerShell: How to Use Group-Object with Multiple Properties
PowerShell: How to Find Duplicate Values in Array
PowerShell: How to Compare Two Arrays

Recently, I got a requirement to sort an array alphabetically in PowerShell. PowerShell provides different methods for Sorting an array alphabetically. One of the simple and powerful cmdlet called Sort-Object for sorting a PowerShell array. In this blog post, we will explore how to use this cmdlet to sort an array alphabetically in PowerShell with complete examples.

Now, let us see different ways to sort an array alphabetically in PowerShell.

1. Using Sort-Object Cmdlet

The Sort-Object cmdlet is a versatile command in PowerShell that allows you to sort data in an array or a list based on object properties. By default, when you sort strings, it sorts them in ascending alphabetical order. Here’s a basic example:

# Create an array of strings
$names = 'Smith', 'Anderson', 'Wright', 'Mitchell'
# Sort the array alphabetically
$sortedNames = $names | Sort-Object
# Display the sorted array
$sortedNames

In this example, the output will display the names in alphabetical order: Anderson, Mitchell, Smith, Wright.

I have executed the full PowerShell script using VS code, and you can see the output in the screenshot below:

Sort Array Alphabetically In PowerShell

2. Sort a PowerShell Array in Descending Order

If you want to sort the array in descending order in PowerShell, you can use the -Descending switch parameter:

Here is a complete PowerShell script:

# Create an array of strings
$names = 'Smith', 'Anderson', 'Wright', 'Mitchell'
# Sort the array in descending alphabetical order
$sortedNamesDesc = $names | Sort-Object -Descending
# Display the sorted array
$sortedNamesDesc

You can see the output in the screenshot below:

PowerShell Sort Array Alphabetically

3. Sort PowerShell Array Based on String Length

Here is the script to sort a string array alphabetically using string length in PowerShell.

# Create an array of strings
$names = 'Smith', 'Anderson', 'Wright', 'Mitchell'
# Sort the array based on string length
$sortedByLength = $names | Sort-Object { $_.Length }
# Display the sorted array
$sortedByLength

Here is the output you can see in the screenshot below:

powershell sort string array alphabetically

4. Case-Insensitive Sorting

By default, Sort-Object is case-insensitive when sorting strings in PowerShell. However, if you need to perform a case-sensitive sort, you can use the -CaseSensitive switch in PowerShell array.

# Create an array of strings
$names = 'Smith', 'Anderson', 'Wright', 'Mitchell'
# Case-sensitive alphabetical sort
$caseSensitiveSort = $names | Sort-Object -CaseSensitive
# Display the sorted array
$caseSensitiveSort

5. Sorting with Custom Comparisons

# Custom comparer for reverse alphabetical sorting
$comparer = [System.Collections.Generic.Comparer[string]]::Create({ param($x, $y) return [string]::CompareOrdinal($y, $x)
})
# Convert the array to a list
$list = [System.Collections.Generic.List[string]]$names
# Use the Sort method with the custom comparer
$list.Sort($comparer)
# Display the sorted list
$list

Conclusion

In this PowerShell tutorial, I have explained how to sort array alphabetically In PowerShell using different methods with examples.

You may also like:

:/>  Как узнать серийный номер тома жесткого диска


Do you need to know about PowerShell sort arrays? In this PowerShell tutorial, I will explain how to sort an array in PowerShell using various methods and real examples.

An array is a data structure that holds a collection of items. These items can be of any data type, and in PowerShell, arrays can even hold items of different types. Arrays are incredibly useful for storing and manipulating sets of data.

Let us explore different methods to sort a PowerShell array.

Sorting a PowerShell Array with Sort-Object

The primary cmdlet for sorting in PowerShell is Sort-Object. This cmdlet sorts objects in ascending or descending order based on object property values. If you don’t specify a property, PowerShell will sort based on the default property for the object type.

Basic Sorting

Here’s a simple example of sorting an array of numbers in PowerShell using sort-object:

$array = 3, 1, 4, 1, 5, 9, 2
$sortedArray = $array | Sort-Object
$sortedArray

This will output the numbers in ascending order:

1
1
2
3
4
5
9

Here is another example of how to sort a string array in PowerShell.

# Define a string array
$stringArray = 'orange', 'apple', 'banana'
# Sort the array in ascending order using Sort-Object
$sortedArray = $stringArray | Sort-Object
# Output the sorted array
$sortedArray

This script will output the strings ‘apple’, ‘banana’, and ‘orange’ in ascending alphabetical order. You can see the output in the screenshot below after I executed the PowerShell script using VS code:

Sort an Array in PowerShell

If you wanted to sort in descending order, you would modify the Sort-Object line to include the -Descending parameter:

# Sort the array in descending order
$sortedArray = $stringArray | Sort-Object -Descending

You can see the output in the screenshot below; I have used VS code; you can use any editor to execute the PowerShell script.

PowerShell sort array

Sorting in Descending Order

To sort a PowerShell array in descending order, use the -Descending switch:

$sortedArray = $array | Sort-Object -Descending
$sortedArray

Sort String Array in PowerShell

You can also sort a string array in PowerShell. By default, the sort is case-insensitive:

$stringArray = 'Banana', 'apple', 'Cherry'
$sortedStringArray = $stringArray | Sort-Object
$sortedStringArray

This sorts the strings in alphabetical order:

apple
Banana
Cherry

Sort an Array in PowerShell using Custom Expression

Let us see how to sort an array in PowerShell using a custom expression. You can sort based on expressions, such as parts of a string or mathematical calculations:

$array = 'a1', 'a10', 'a2', 'a3'
$sortedArray = $array | Sort-Object { [int]($_.Substring(1)) }
$sortedArray

This will sort the array based on the numerical part of each string:

a1
a2
a3
a10

Sort a PowerShell Array with Multiple Properties

You can also sort a PowerShell array by multiple properties. This is useful when you have complex objects, and you want to sort by one property, then another:

$people = @( @{ Name = 'John'; Age = 30 }, @{ Name = 'Jane'; Age = 25 }, @{ Name = 'John'; Age = 22 }
)
$sortedPeople = $people | Sort-Object -Property Name, Age
$sortedPeople

The above PowerShell script will sort people by name and then by age within each name.

:/>  Регулярные выражения power shell

Sort Array with Hash Tables in PowerShell

Let me show you how to sort an array with hash tables in PowerShell.You can use hash tables to specify different sorts for different properties:

$sortedPeople = $people | Sort-Object -Property @{Expression="Name";Descending=$false}, @{Expression="Age";Descending=$true}
$sortedPeople

This sorts by name in ascending order and then by age in descending order.

Conclusion

Sorting arrays in PowerShell is a very common requirement, and we can achieve it using various methods. The Sort-Object cmdlet is the go-to for most sorting tasks, with options for sorting in ascending or descending order, case sensitivity, and unique value sorting.

In this PowerShell tutorial, I have explained how to work with PowerShell array sorting, especially different methods to sort a PowerShell array.

Yu may also like:

AAAA z
BBBB y
AAAA z
BBBB z
CCCC y
AAAA x
BBBB z 

I want to find lines with “z” and sort the resulting set according to last column.

What I have tried:

Get-Content .\test.txt | Select-String | Sort-Object { [double]$_.split()[-1] }

This gives error:

Sort-Object : Method invocation failed because [Microsoft.PowerShell.Commands.MatchInfo] does not contain a method name
d .
At line: :
+ ... test.txt | Select-String | Sort-Object { [double]$_.split()[-1] }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidResult: (AAAA z :PSObject) [Sort-Object], RuntimeException + FullyQualifiedErrorId : ExpressionEvaluation,Microsoft.PowerShell.Commands.SortObjectCommand


solution

Solution 1

 = Import-Csv -Path .\test.txt -Delimiter -Header ,, | Where-Object -Property Two -Like | Sort-Object { ].Three }

Note, I used int rather than double since all the values are integral numbers.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

 

Print
Answers RSS

Top Experts
Last 24hrsThis month



CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900