Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 686
Snowung Avatar asked Mar 07 '26 02:03

Snowung


1 Answers

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

# Create an empty Hashtable with a capacity equal or greater than the number of
# elements in $Profil
$ProfilSorted = [Hashtable]::New($Profil.Count)

foreach ($KeyAndValue in $Profil.GetEnumerator())
{
    # RegEx split on a comma followed by whitespace.
    [String[]]$Value = $KeyAndValue.Value -split ',\s*' |
        Sort-Object

    # Convert $Value from array of Strings to single String joined by commas.
    [String]$Value = $Value -join ','

    $ProfilSorted.Add($KeyAndValue.Key, $Value)
}

$Profil = $ProfilSorted
$Profil

You may want to consider storing the value as an array of strings [String[]], instead of relying on text-splicing.

like image 187
Just-Harry Avatar answered Mar 10 '26 03:03

Just-Harry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!