In a PowerShell script I needed to sort a hash table by byte value (not alphabetically, lowercase parameters will be listed after uppercase ones). An example for this requirement is the Amazon Product Advertising API.

Consider the following hashtable as an example:

Example Hash Table powershell Download
$params = @{}
$params.Add("AssociateTag", "dummy")
$params.Add("AWSAccessKeyId", "AKIAIOSFODNN7EXAMPLE")
$params.Add("IdType", "0679722769")
$params.Add("Operation", "ItemLookup")

If we use the Sort-Object to order the list (note that we need to use the GetEnumerator method):

Sort Hash Table powershell Download
$params.GetEnumerator() | Sort-Object Name

We will get the following result:

Sort Results powershell Download
Name                           Value
----                           -----
AssociateTag                   dummy
AWSAccessKeyId                 AKIAIOSFODNN7EXAMPLE
IdType                         0679722769
Operation                      ItemLookup

If you use the -CaseSensitive switch the resulting order will remain the same.

I came up with the following code (download link below) to sort the hashtable in the required order:

Sort-Binary powershell Download
function Sort-Binary {
    param(
        [Parameter(Mandatory = $true,  ValueFromPipeline = $true)][HashTable]$HashTable,
        [Switch]$Descending
    )
    $keys = $HashTable.Keys | ForEach {$_}
    for ($i = 0; $i -lt $keys.Count - 1; $i++) {
        for ($j = $i + 1; $j -lt $keys.Count; $j++) {
            if ($Descending) {$swap = [String]::CompareOrdinal($keys[$i], $keys[$j]) -lt 0} else {$swap = [String]::CompareOrdinal($keys[$i], $keys[$j]) -gt 0}
            if ($swap) {$keys[$i], $keys[$j] = $keys[$j], $keys[$i]}
        }
    }

	$list = New-Object System.Collections.Specialized.OrderedDictionary
	$keys | ForEach { $list.Add($_, $HashTable[$_]) }

	return $list
}

Let's try that:

Sort-Binary Example powershell Download
$params = @{}
$params.Add("AssociateTag", "dummy")
$params.Add("AWSAccessKeyId", "AKIAIOSFODNN7EXAMPLE")
$params.Add("IdType", "0679722769")
$params.Add("Operation", "ItemLookup")

$params | Sort-Binary

Name                           Value
----                           -----
AWSAccessKeyId                 AKIAIOSFODNN7EXAMPLE
AssociateTag                   dummy
IdType                         0679722769
Operation                      ItemLookup

Download PowerShell Script