Sort multiple values in hashtable in powershell
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
foreach($value in $Profil.GetEnumerator() | Sort Value) $value.Value
3 Answers
3
$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*'
$Profil = $ProfilSorted
$Profil
You may want to consider storing the value as an array of strings [String]
, instead of relying on text-splicing.
[String]
This should work:
$newProfil = @
$Profil.GetEnumerator() | foreach Sort-Object) -join ','
$newProfil.add($_.Key, $newValue)
$newProfil
Perfect ! Thanks it's work :)
– Snowung
Aug 23 at 15:01
The following updates the hash table in place using a foreach
statement (I've replaced $Profil
with $hash
, to avoid confusion with the automatic $PROFILE
variable.)
foreach
$Profil
$hash
$PROFILE
foreach ($key in @($hash.Keys)) Sort-Object) -join ','
$hash # output the updated hash table
$hash.Keys
enumerates the hashtable's keys for use in the loop.
$hash.Keys
@(...)
.Keys
$hash[$key]
inside the loop accesses a single entry for the key at hand.
$hash[$key]
.
$hash.key
-split ', *'
splits the existing entry value into tokens by commas followed by zero or more (*
) spaces.
-split ', *'
*
| Sort-Object
sorts the resulting tokens.
| Sort-Object
-join ','
joins the sorted tokens with a comma as the separator.
-join ','
Using the pipeline is also an option, but will generally be slower (though that may not matter in many use cases):
@($hash.Keys) | ForEach-Object Sort-Object) -join ','
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thanks for this comment ! It's very helpful !
– Snowung
Aug 23 at 15:02