Sorting Help for a Newbie to PowerShell

This topic contains 4 replies, has 4 voices, and was last updated by  Adam Bertram 7 months, 3 weeks ago.

  • Author
    Posts
  • #65217

    Scott Evans
    Participant

    I've got a file with a long list of integers and I need to identify the largest integer. I tried

    $max_delay = Get-Content caca1.txt | sort | select-object -last 1

    I thought this put the largest integer at the bottom and I could assign it to a variable. (I'm used to sort -n in unix.) I created a test file with 1000 as the largest value, but got 829 (the next highest value) instead. When I looked at the sort it was something like...
    1000
    109
    258
    331
    699
    744
    829
    How can I identify the largest integer in the file?

  • #65220

    Daniel Krebs
    Moderator

    You'll need to cast or convert the individual lines which are strings into the data type integer to be able to sort by largest.

    Example:

    $max_delay = Get-Content caca1.txt | ForEach-Object { [System.Convert]::ToInt32($PSItem.Trim()) } | Sort-Object | Select-Object -Last 1
    $max_delay = Get-Content caca1.txt | ForEach-Object { [System.Int32]$PSItem.Trim() } | Sort-Object | Select-Object -Last 1
    

    In the future, please post general PowerShell questions like this in the "PowerShell Q&A" subforum instead of "Pester".

  • #65221

    Richard Siddaway
    Moderator

    The problem is that Get-Content is returning an array of strings rather than integers so sort works on a string sort rather than a numeric sort

    These options should work

    Get-Content .\num.txt | foreach {$psitem -as [int]} | sort | select -Last 1

    Get-Content .\num.txt | foreach {[int]$psitem} | sort | select -Last 1

    Get-Content .\num.txt | foreach ToInt32($_) | sort | select -Last 1

    I've put your sample numbers into num.txt

  • #65232

    Scott Evans
    Participant

    The file I'm working with is a temporary file I created by pulling the numbers from a larger text file. Is there anyway I can create this temp file in the correct format to begin with?

  • #65242

    Adam Bertram
    Moderator

    Moved question to PowerShell Q&A.

You must be logged in to reply to this topic.