Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort array as number but not string in powershell

Would like to convert a string with collection of numbers into a sorted array object in PowerShell. However, it was sorted based on the ASCII value of each character, but not the value of number. For example: I have

[string]$PortException = "3128,53,3389,5985,5986"

When sort with Sort-Object:

$PortExceptionArray = ($PortException.Split(',') | Sort-Object)

The outcome to the array is in the order of:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

3128
3389
53
5985
5986

However, it is expect that "53" will be on the top.

Any thoguht?

>Solution :

You can cast the string to an integer:

$PortExceptionArray = $PortException -split ',' | Sort-Object -Property {[int]$_ }

Output:

53
3128
3389
5985
5986
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading