0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

powershellで配列+ハッシュテーブルをいい感じでソートしたい。

Posted at
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 "-----"
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?