Search code examples
powershellsortinghashtabletrim

Sort multiple values in hashtable in powershell


I have a hashtable in PowerShell that looks like this:

Profil = @{
"Jason" = "P2, P4, P1";
"Mick" = "P1";
"Rocky" = "P4, P5";
"Natasha" = "P9, P4, P1"
}

I need to remove whitespace and sort like :

Profil = @{
"Jason" = "P1,P2,P4";
"Mick" = "P1";
"Rocky" = "P4,P5";
"Natasha" = "P1,P4,P9"
}

I try foreach($value in $Profil.GetEnumerator() | Sort Value) {$value.Value} but doesn't work


Solution

  • This should work:

    $newProfil = @{}
    $Profil.GetEnumerator() | foreach {
    
        $newValue = (($_.Value -replace "\s","") -split ',' | Sort-Object) -join ','
        $newProfil.add($_.Key, $newValue)
    }
    
    $newProfil