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

PowerShell: Activate Remote Windows

$remoteWindows="SHERVER01","SHERVER02"$licenseKey="XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"function activateWindows{ param( [string]$key ) $licensingService = get-wmiObject -query "select * from SoftwareLicensingService" -computername $env:computername;…

Convert LastLogon Date From Number to Date Time

We have a case where our Admins have generated a CSV file with information about…

PowerShell: Obtain Computer Account Parent Container from Invoke-Command

# ObtainComputerAccountParentContainer.ps1# This is a demonstration of how to pass function into an invoke-command as…