古いバージョンのPowerShellとの互換性のために、次のコマンドレットを検討してください。
Function Order-Keys {
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)][HashTable]$HashTable,
[Parameter(Mandatory = $false, Position = 1)][ScriptBlock]$Function,
[Switch]$Descending
)
$Keys = $HashTable.Keys | ForEach {$_} # Copy HashTable + KeyCollection
For ($i = 0; $i -lt $Keys.Count - 1; $i++) {
For ($j = $i + 1; $j -lt $Keys.Count; $j++) {
$a = $Keys[$i]
$b = $Keys[$j]
If ($Function -is "ScriptBlock") {
$a = $HashTable[$a] | ForEach $Function
$b = $HashTable[$b] | ForEach $Function
}
If ($Descending) {
$Swap = $a -lt $b
}
Else
{
$Swap = $a -gt $b
}
If ($Swap) {
$Keys[$i], $Keys[$j] = $Keys[$j], $Keys[$i]
}
}
}
Return $Keys
}
このコマンドレットは、関数定義順に並べられたキーのリストを返します。
名前順:
$HashTable | Order-Keys | ForEach {Write-Host $_ $HashTable[$_]}
Germany Berlin
Italy Rome
Spain Madrid
Switzerland Bern
値で並べ替え:
$HashTable | Order-Keys {$_} | ForEach {Write-Host $_ $HashTable[$_]}
Germany Berlin
Switzerland Bern
Spain Madrid
Italy Rome
ハッシュテーブルをネストすることも検討してください。
$HashTable = @{
Switzerland = @{Order = 1; Capital = "Berne"}
Germany = @{Order = 2; Capital = "Berlin"}
Spain = @{Order = 3; Capital = "Madrid"}
Italy = @{Order = 4; Capital = "Rome"}
}
たとえば、(ハッシュされた)注文プロパティで並べ替えて、キー(国)を返します。
$HashTable | Order-Keys {$_.Order} | ForEach {$_}
または、事前定義された大文字で並べ替え(降順)します。
$HashTable | Order-Keys {$_.Capital} -Descending | ForEach {$_}