2

I am having below PowerShell script which does not result in the sorting order I want.

$string = @("Project-a1-1", "Project-a1-10", "Project-a1-2", "Project-a1-5", "Project-a1-6", "Project-a1-8")

$myobjecttosort=@()

$string | ForEach{
    $myobjecttosort+=New-Object PSObject -Property @{    
    'String'=$_
    'Numeric'=[int]([regex]::Match($_,'\d+')).Value
    }
}

$myobjecttosort | Sort-Object Numeric | Select Numeric,String | Format-Table -AutoSize

The output of the above script:

Numeric String


  1 Project-a1-5
  1 Project-a1-6
  1 Project-a1-8
  1 Project-a1-1
  1 Project-a1-10
  1 Project-a1-2

Required Output

  1 Project-a1-1
  2 Project-a1-2
  3 Project-a1-5
  4 Project-a1-6
  5 Project-a1-8
  6 Project-a1-10

Also, I want always output to be returned as the last value so here output would be Project-a1-10

1 Answer 1

2

Sort-Object accepts a script block allowing for a more robust sort. With that said, just like any other object in the pipeline, the objects are accessible via $PSItem, or $_. So, a quick way to go about this is splitting the string at the - selecting just the ending numerical digits, then casting [int] to the result to sort by.

$string = "Project-a1-1", "Project-a1-10", "Project-a1-2", "Project-a1-5", "Project-a1-6", "Project-a1-8"
$string | 
    Sort-Object -Property { [int]($_ -replace '^.*?(?=\d+$)') } |
    % { $i = 1 } {
        '{0} {1}' -f $i++, $_
    }

The above yields:

1 Project-a1-1
2 Project-a1-2
3 Project-a1-5
4 Project-a1-6
5 Project-a1-8
6 Project-a1-10

Passing the sorted items to % (alias to Foreach-Object), we can then format a new string giving it an index # to each string starting at 1.

Sign up to request clarification or add additional context in comments.

4 Comments

I think this each one is a good answer, however, what If I want to remove indices from output like 1,2,3...?
@DevDeveloper, I dont believe I understand what it is you're after. Can you elaborate a bit more?
I mean to say if input array was like this, Project-a1-v1, Project-a1-v10, Project-a1-v14, how to sort them. this does not work. [string[]]$arrayFromFile = Get-Content -Path 'd:\log.txt' $finalArray= $arrayFromFile.split('') $finalArray | Sort-Object -Property {[int] substring(($_ -split '-')[-1],1) } | Select-Object -Last 1,
That wasnt in the question, but I've updated my answer. Just using -Replace rather than -Split to leave just the last numbers to sort by. Is that what you're after?

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.