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
0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.