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

Sorting string of numeric in powershell

I have retrieved an array of strings that are

0.0.1
0.0.10
0.0.2

Since this is string with multiple dots I had to remove dots to compare them which I did it following way

$array = $r.Links.outerText.replace('/','') | 
Where {$_ -notmatch $filter} | 
% {$_ -replace('\.', '')} | 
sort {[double]$_}

This gives me

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

001                                                                                                                                                                       
002
010

but now I want to retrieve the original value of the last value which is 0.0.10.
How should I do that? or is there any other approach to sort without replacing the dots?

>Solution :

Do the string manipulation inside the scriptblock passed to sort:

... |sort {[double]($_ -replace '\.')}

This way the sorting still works, but the underlying data stays intact


With this in mind, for version-like strings it’s probably better to cast to [version] and let the internal comparison logic of that data type work it’s magic:

PS ~> -split '0.0.1 0.0.10 0.0.2' |sort {[version]$_}
0.0.1
0.0.2
0.0.10
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