Home > Blockchain >  PowerShell script to sort an array ascending order and return last value
PowerShell script to sort an array ascending order and return last value

Time:12-30

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

CodePudding user response:

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.

CodePudding user response:

You can use the Sort-Object

# Sort the array in ascending order
$sortedArray = $array | Sort-Object

# Get the last value in the sorted array
$lastValue = $sortedArray | Select-Object -Last 1
  • Related