Numerical sorting?

Is there any method of sorting files numerically as in 1,2,3…9,10,11, as opposed to literally, as in 1,10,11,2,3,4…?

You’d have to convert those strings to numbers first, and how you do that will depend on what else is in the file name. (is it just 1.txt, 2.txt, etc? Or file-1.txt, etc?)

gci |Sort-Object { [int]$_.basename }

Can’t rely on only numbers in file name

PS> [int]file01.txt
At line:1 char:6

  • [int]file01.txt
  •  ~~~~~~~~~~

Unexpected token ‘file01.txt’ in expression or statement.
+ CategoryInfo : ParserError: (:slight_smile: [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken

This will sort the file names that contain numbers, but makes everything else go out of order:

Get-ChildItem | Sort-Object {$_.BaseName -replace "\D+" -as [Int]}

I tried a few things like this, but no luck:

Sort-Object {If ($_.BaseName -match '\d+' -eq "True") {$_.BaseName -replace "\D+" -as [Int]}}

So I’m guessing it’s not possible to selectively sort only certain objects. At least not in one line.

I was giving you something to go on. We still need to know what you’re working with to give an accurate answer.

I can only assume you’re writing logs with similar names and the int. For that I’d just sort by last write time.