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
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With