1

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
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
Geo V
  • 121
  • 1
  • 10

1 Answers1

4

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
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37