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]





Thanks for this comment ! It's very helpful !
– Snowung
Aug 23 at 15:02



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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)