1

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

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?

user1298426
  • 3,467
  • 15
  • 50
  • 96

1 Answers1

4

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
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Wasn't aware of [version] type. Thanks for pointing that out. I just relaced [double] with [version] to make it work. – user1298426 Feb 04 '22 at 10:43
  • 1
    Provided the strings *are* versions, the ```[version]``` approach is probably more reliable - for example the string manipulation route will give an unexpected sort order for e.g. ```0.28.1``` (=> 281) vs ```0.2.91``` (=> 291). – mclayton Feb 04 '22 at 14:34