Search code examples
powershellcsvsortingsort-object

Powershell Import-CSV wont sort


In Powershell, I'm attempting to import a CSV file and sort it based on its header name and pipe that to format-table. However I've tried every which way to get it to sort correctly and cant seem to figure it out, any ideas?

CSV:

Price,OnHands,Status 
43.73,6,INACTIVE
33,36,CLEARANCE
9.62,3,CLEARANCE
57.8,22,ACTIVE
69.57,16,ACTIVE
22,15,CLEARANCE

aka

Price  OnHands Status
------ ------- ------
43.73  6       INACTIVE  
33.0   36      CLEARANCE 
9.62   3       CLEARANCE 
57.8   22      ACTIVE    
69.57  16      ACTIVE    
22.0   15      CLEARANCE 

I've tried the line below, with single, double, and no quotes and as an integer.

$data = Import-Csv -Path $PathnNameCSV | Sort-Object -Property 'OnHands' -Descending

Also tried just using sort, perhaps my syntax is wrong or the wrong combination somewhere.

$data = Import-Csv -Path $PathnNameCSV | sort -Property 'OnHands' -Descending

My intended result would be:

Price  OnHands Status
------ ------- ------
33.0   36      CLEARANCE 
57.8   22      ACTIVE    
69.57  16      ACTIVE 
22.0   15      CLEARANCE 
43.73  6       INACTIVE 
9.62   3       CLEARANCE 

Solution

  • Import-Csv -Path $PathnNameCSV |
        Sort-Object -Property { [int]$_.OnHands } -Descending
    
    Price OnHands Status   
    ----- ------- -------  
    33    36      CLEARANCE
    57.8  22      ACTIVE   
    69.57 16      ACTIVE   
    22    15      CLEARANCE
    43.73 6       INACTIVE 
    9.62  3       CLEARANCE
    

    More complex examples at official docs Use a hash table to sort properties in ascending and descending order