Posted On July 28, 2020

PowerShell: Sorting an Array of Strings as Numbers

kimconnect 0 comments
blog.KimConnect.com >> Codes >> 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 *

Related Post

WordPress: Gold Price Widget CSS

Here's a sample of CSS Code to customize the display of the WordPress' Gold Pricing…

Search for Windows computers in a certain subnet using Active Directory

# Search for Windows computers in a certain subnet using Active Directory $subnetQuery='10.10' $filterString='2016' $computers=Get-ADComputer…

Basic HTML and HTML5: Create a Bulleted Unordered List

<h2>CatPhotoApp</h2><main><p>Click here to view more <a href="#">cat photos</a>.</p><a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying…