Author Posts

February 24, 2017 at 5:40 pm

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?

February 24, 2017 at 6:20 pm

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".

February 24, 2017 at 6:23 pm

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

February 24, 2017 at 8:24 pm

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?

February 24, 2017 at 8:56 pm

Moved question to PowerShell Q&A.