PowerShell: Sorting an Array of Strings as Numbers

This is a useful function to sort a list of computer names. The built-in sorting algorithm currently does NOT account for the numerical portion of each string. Hence, this customized function will make that possible.

Be advised that this function peruses Hash Table as an intermediary step because its sorting algorithm is faster than standard arrays. Moreover, it will remove any duplicates from the original input. That may be good or bad, depending on the requirements.

function sortArrayStringAsNumbers([string[]]$names){
    $hashTable=@{}
    $maxLength=($names | Measure-Object -Maximum -Property Length).Maximum
    foreach ($name in $names){
        #[int]$x=.{[void]($name -match '(?:.(\d+))+$');$matches[1]}
        #$x=.{[void]($name -match '(?:.(\d+)+)$');@($name.substring(0,$name.length-$matches[1].length),$matches[1])}
        $originalName=$name
        $x=.{Clear-Variable matches
            [void]($name -match '(?:.(\d+)+)\w{0,}$');
            if($matches){
                [int]$trailingNonDigits=([regex]::match($name,'\D+$').value).length
                if($trailingNonDigits){
                    $name=$name.substring(0,$name.length-$trailingNonDigits)
                }
                return ($name.substring(0,$name.length-$matches[1].length))+$matches[1].PadLeft($maxLength,'0');
            }else{
                return $name+''.PadLeft($maxLength,'0');
            }}
        $hashTable.Add($originalName,$x)
        }
    $sorted=foreach($item in $hashTable.GetEnumerator() | Sort Value){$item.Name}
    return $sorted
}

sortArrayStringAsNumbers $computerNames

Leave a Reply

Your email address will not be published. Required fields are marked *