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){
    $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])}
        $x=.{Clear-Variable matches
            [void]($name -match '(?:.(\d+)+)\w{0,}$');
                return ($name.substring(0,$name.length-$matches[1].length))+$matches[1].PadLeft($maxLength,'0');
                return $name+''.PadLeft($maxLength,'0');
    $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 *