Home > front end >  Powershell Objects Sorting On Property - Descending - Not working
Powershell Objects Sorting On Property - Descending - Not working

Time:01-30

I am sorting the contents of the a text file as below

APPLE|FINAL|20220122065900|0
APPLLE|PRE|20220122061500|0
MANGO|PRE|20220126113400|0
MANGO|PRE|20220125102200|0
MANGO|ASSYN|20220125102200|0
$file = Get-Content D:\FOXXXX\DOWNTIME\POWER\test.txt
Foreach($line in  $file)
{
     New-Object PSObject -Property @{
        "t1" = $line.split("|")[0]
        "t2" = $line.split("|")[1]
 } | Sort-Object -Property t1 -Descending |Select-Object t1, t2

} 

I am getting the following output with no sorting. Please let me know what I am doing wrong

t1     t2   
--     --   
APPLE  FINAL
APPLLE PRE  
MANGO  PRE  
MANGO  PRE  
MANGO  ASSYN

CodePudding user response:

You're sorting each element of the collection instead of sorting all the collection, in other words, Sort-Object should be outside the loop:

$collection = Foreach($line in $file)
{
    New-Object PSObject -Property @{
        "t1" = $line.split("|")[0]
        "t2" = $line.split("|")[1]
    }
}

$collection | Sort-Object -Property t1 -Descending

On the other hand, your text file is pipe delimited, you can use ConvertFrom-Csv or Import-Csv (if from a file) to convert it into an object:

@'
APPLE|FINAL|20220122065900|0
APPLLE|PRE|20220122061500|0
MANGO|PRE|20220126113400|0
MANGO|PRE|20220125102200|0
MANGO|ASSYN|20220125102200|0
'@ | ConvertFrom-Csv -Delimiter '|' -Header T1, T2 |
Sort-Object T1 -Descending
  •  Tags:  
  • Related