Windows Vista Forums

Sorting a hashtable
  1. #1


    johnjhamm@gmail.com Guest

    Sorting a hashtable

    I wrote this command to show the size of all sub-folders in a folder:

    dir | ? { $_.PsIsContainer } | % { $t=0;dir -rec $_.Name | % {$t +=
    $_.Length }; @{$_.Name=$t}}

    This outputs:

    Name Value
    ---- -----
    Avaya 1887047
    C# 294
    PowerShell 8643
    Regular Expressions 161
    Sql 3914
    Windows 1964032


    Now, I'd like to sort them by size (or the "Value" property of the
    Hashtable). I append "sort value" to the end of my command:

    dir | ? { $_.PsIsContainer } | % { $t=0;dir -rec $_.Name | % {$t +=
    $_.Length }; @{$_.Name=$t}} | sort value



    But I get:

    Name Value
    ---- -----
    Regular Expressions 161
    Sql 3914
    Windows 1964032
    Avaya 1887047
    C# 294
    PowerShell 8643


    How do I get this to sort?!


      My System SpecsSystem Spec

  2. #2


    Sung M Kim Guest

    Re: Sorting a hashtable

    There should be other ways to accomplish sorting Hashtable data by
    "value"s, but the easiest way is to access the "Values" property of
    pipeline object of type Hashtable.

    dir | ? {$_.PsIsContainer} | % { $t=0; ls -r $_.Name | % {$t +=
    $_.Length }; @{ $_.Name=$t } } | sort {$_.Values}

    In the last section of the pipeline, "sort-object"'s input object takes
    in script block argument and sort by the "Values" property of the
    hashtable object.


      My System SpecsSystem Spec

Sorting a hashtable problems?

Similar Threads
Thread Thread Starter Forum Replies Last Post
Hashtable - problem with getting key and value Marek Zegarek PowerShell 0 27 Jul 2009
array or hashtable Mo PowerShell 3 01 Jul 2009
I can't access this hashtable RickB PowerShell 1 23 Sep 2008
How to sort a hashtable? Tibor Soos PowerShell 3 31 Jan 2008
sorting on hashtable values Neil Chambers PowerShell 3 08 Apr 2007