hashtable sort.ps1
function Process-HashTables {
param (
[Parameter(Mandatory = $true)]
[array]$hashTables, # 処理対象のハッシュテーブルの配列
[string[]]$duplicateKeys, # 重複を削除する列のキー名配列
$sortKeysAndOrder # ソートする列とその順序を定義したハッシュテーブル
)
# ソート処理
if ($sortKeysAndOrder) {
$hashTables = $hashTables | Sort-Object $sortKeysAndOrder
}
# 重複データ削除
if ($duplicateKeys) {
$seen = @{}
$uniqueResult = @()
foreach ($hashTable in $hashTables) {
$keyValues = $duplicateKeys | ForEach-Object { $hashTable.$_ }
$compositeKey = $keyValues -join '|'
if (-not $seen.ContainsKey($compositeKey)) {
$seen[$compositeKey] = $true
$uniqueResult += $hashTable
}
}
$hashTables = $uniqueResult
}
return $hashTables
}
# データセット
$data = @(
[ordered]@{ key1 = "100" ; key2 = "65" ; key3 = "2024/04/05 20:50:14" ; key4 = "data~5" },
[ordered]@{ key1 = "190" ; key2 = "45" ; key3 = "2024/04/05 20:50:14" ; key4 = "data~1" },
[ordered]@{ key1 = "100" ; key2 = "55" ; key3 = "2024/04/05 20:50:14" ; key4 = "data~3" },
[ordered]@{ key1 = "190" ; key2 = "35" ; key3 = "2024/04/05 20:50:11" ; key4 = "data~2" },
[ordered]@{ key1 = "100" ; key2 = "25" ; key3 = "2024/04/05 20:50:11" ; key4 = "data~4" },
[ordered]@{ key1 = "100" ; key2 = "15" ; key3 = "2024/04/05 20:50:11" ; key4 = "data~6" }
)
# 重複削除対象列
$duplicateColumns = @('key1')
# ソート対象列と順序
$sortColumnsAndOrder = @(
@{ exp = { $_.key1 }; des = $true },
@{ exp = { $_.key2 }; des = $true },
@{ exp = { $_.key3 }; asc = $true }
)
# データ処理(ソートと重複削除)
$resultData = Process-HashTables -hashTables $data -duplicateKeys $duplicateColumns -sortKeysAndOrder $sortColumnsAndOrder
# 結果を1列ごとに表示
foreach ($hashTable in $resultData) {
$hashTable.GetEnumerator() | Sort-Object Name | ForEach-Object {
Write-Output "$($_.Name) = $($_.Value)"
}
Write-Output "-----"
}