Search code examples
powershellpowershell-2.0powershell-3.0

Powershell not sorting by Name


I am trying to sort the hashtable by Name.

This is the hashtable

$hashtable = @{}
$hashtable.Add('16',  'Name = $4 000 000,Value = $4 000 000');
$hashtable.Add('5','Name = $600 000Value = $600 000');
$hashtable.Add('12','Name = $1 750 000;Value = $1 750 000');
$hashtable.Add('10','Name = $1 200 000;Value = $1 200 000');
$hashtable.Add('2','Name = $300 000;Value = $300 000');
$hashtable.Add('8','Name = $900 000;Value = $900 000');
$hashtable.Add('17','Name = $4 000 000;Value = $4 000 000');
$hashtable.Add('11','Name = $1 500 000;Value = $1 500 000');
$hashtable.Add('1','Name = $1000000;Value = $200 000');
$hashtable.Add('9','Name = $1 000 000;Value = $1 000 000');
$hashtable.Add('14','Name = $2 500 000;Value = $2 500 000');
$hashtable.Add('7','Name = $800 000;Value = $800 000');
$hashtable.Add('15','Name = $3 000 000;Value = $3 000 000');
$hashtable.Add('6','Name = $700 000;Value = $700 000');
$hashtable.Add('4','Name = $500 000;Value = $500 000');
$hashtable.Add('13','Name = $2 000 000;Value = $2 000 000');

$hashtable.GetEnumerator() | sort -Property name 

I have used $hashtable.GetEnumerator() | sort -Property name to sort by Name but its not sorting.

Any suggestions?


Solution

  • You are creating a Hashtable with numeric Keys and as Value strings like Name = Something; Value = Something (and sometimes the ; is a ,) in there..

    My guess is you want an array of objects instead where each object has 3 properties: an Id, Name and Value (although in your sample data I don't understand why Name would be a currency value like Value)

    By creating such an object array you can sort on any of the properties.

    As example I have rewritten your Hashtable declaration to become a CSV formatted string where I have taken the liberty of changing the property names to Id, Price and Value

    $table = @'
    Id,Price,Value
    16,$4 000 000,$4 000 000
    5,$600 000,$600 000
    12,$1 750 000,$1 750 000
    10,$1 200 000,$1 200 000
    2,$300 000,$300 000
    8,$900 000,$900 000
    17,$4 000 000,$4 000 000
    11,$1 500 000,$1 500 000
    1,$1000000,$200 000
    9,$1 000 000,$1 000 000
    14,$2 500 000,$2 500 000
    7,$800 000,$800 000
    15,$3 000 000,$3 000 000
    6,$700 000,$700 000
    4,$500 000,$500 000
    13,$2 000 000,$2 000 000
    '@ | ConvertFrom-Csv
    

    Now you can sort anyway you like, for instance:

    # sort on the `Id` column
    $table | Sort-Object {[int]$_.Id}
    
    # sort on the `Price` column 
    $table | Sort-Object {[int64]($_.Price -replace '\D')}
    

    etc.