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: Copy SMB Share Permissions from Legacy Sources

Scenario:Windows 2008 File Servers migration lacks a built-in function to clone Share Permissions - Get-SmbShareAccess…

PowerShell: Remove an A-Host Record within Active Directory Integrated DNS Domain

Warning: this code is NOT 'production ready'. Please review and test on DEV environments carefully…

PowerShell: Script to Apply Windows Update on 2016 Server

8/7/2020: there's a more updated version available here. # Update-Remote-Windows-2016-Servers.ps1$servers="SERVER1","SERVER2"function applyWindowsUpdates{ [CmdletBinding()] param ( [parameter(Mandatory=$true,Position=1)]…
Other project: DragonCoin.com