How to Sort IP Addresses in PowerShell (With Example)


Often you may want to sort a list of IP addresses in a text file using PowerShell.

You can use the following basic syntax to do so:

gc ip_list.txt | sort { $_ -replace '\d+', { $_.Value.PadLeft(3, '0') } }

This particular example sorts the IP addresses in the file named ip_list.txt.

Note that we use the PadLeft() function to pad each set of numbers in each IP addresses with three zeros on the left side.

We are then able to use the sort function to sort the IP addresses based on the numeric values.

Note: The command gc is simply an alias for Get-Content.

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

Example: How to Sort IP Addresses in PowerShell

Suppose that have a text file named ip_list.txt that contains various IP addresses.

We can use the gc command (or you can type out Get-Content) to view the contents of this file:

The file contains seven total IP addresses but they are not currently sorted in any way.

We can use the following syntax to sort the IP addresses in the file:

gc ip_list.txt | sort { $_ -replace '\d+', { $_.Value.PadLeft(3, '0') } }

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

PowerShell sort IP addresses

Notice that this returns the IP addresses sort in order by numeric values from smallest to largest.

If you’d like, you can add the -Descending operator at the end of the command to instead sort the IP addresses based on numeric values from largest to smallest:

gc ip_list.txt | sort { $_ -replace '\d+', { $_.Value.PadLeft(3, '0') } } -Descending

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

PowerShell sort IP addresses from largest to smallest

Notice that this returns the IP addresses sort in order by numeric values from largest to smallest.

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