Search code examples
powershellsortinginputstructpipeline

Sorting a text by second elem in Powershell


Actually I wrote a powershell script that has an output in this "[name]: [piece]" format (name means the customer name and piece is the number of Coffe the actual customer drank.) This script is called first.ps1

For example:

Josh: 9
Sam: 13
Mark: 2

My problem is that i have to sort this output with another script just like that C: .\first.ps1 | .\second.ps1 (second.ps1 is my sorting script)

in that case "C: .\first.ps1 | .\second.ps1" concerning the previous example my output should be like this

Sam: 13
Josh: 9
Mark: 2

I tried some code and i can succesfully read the input through pipeline but i have some sorting problems i can only sort by names i havent found anything to sort by the numbers

There is the code i tried so far

$input | %{

     $name=$_.split(":")[0]
     $piece=[int]$_.split(":")[1]
     Write-Output $name" "$piece

} | sort -Descending

Thank you in advance


Solution

  • Your first script is actually not a script because it does not contain any code. ;-) Let's call it data. You could create a [PSCustomObject] and use its properties to sort the way you like it ... like this:

    $data = Get-Content -Path C:\sample\data.txt
    
    $data | 
        ForEach-Object {
            $row = $PSItem -split ':'
            [PSCustomObject]@{
                Name        = $row[0].Trim()
                CoffeeCount = [int]$row[1].Trim()
            }
        } |
            Sort-Object -Property CoffeeCount -Descending