0

I have below files which i am reading using a foreach loop.

$GetGeneratedFiles = Get-ChildItem -Path "C:\Script\LF*.csv" -recurse |  % { $_.FullName }

C:\Script\LF_Batch_1.csv
C:\Script\LF_Batch_10.csv
C:\Script\LF_Batch_11.csv
C:\Script\LF_Batch_12.csv
C:\Script\LF_Batch_13.csv
C:\Script\LF_Batch_14.csv
C:\Script\LF_Batch_15.csv
C:\Script\LF_Batch_16.csv
C:\Script\LF_Batch_17.csv
C:\Script\LF_Batch_18.csv
C:\Script\LF_Batch_19.csv
C:\Script\LF_Batch_2.csv
C:\Script\LF_Batch_20.csv
C:\Script\LF_Batch_21.csv etc...upto LF_Batch_.96.csv

Problem is it is reading the files like above not 1,2,3...and so on.

Please need idea how to read in ordered way

Empty Coder
  • 589
  • 6
  • 19
  • You've encountered classical natural order vs ASCIIbetical order issue. Check out this [earlier answer](https://stackoverflow.com/q/5427506/503046) about the same. – vonPryz Sep 17 '20 at 12:02

2 Answers2

1

Solved using below approach

        $GetGeneratedFiles = Get-ChildItem -Path "C:\Script\LF*.csv" -recurse |  % { $_.FullName }

        $ToNatural = { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20) }) }
        
        $GetGeneratedFiles = $GetGeneratedFiles | Sort-Object $ToNatural

Thanks @vonPryz for the reference.

Empty Coder
  • 589
  • 6
  • 19
0

Another way. It's funny how I just did another answer similar to this. A numeric sort on the names.

echo hi | set-content (1,2,10,20 | % tostring LF_Batch_0\.csv)
dir | sort {[void]($_ -match '\d+'); [int]$matches.0}


    Directory: C:\Users\js\foo

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---           9/17/2020  9:14 AM              4 LF_Batch_1.csv
-a---           9/17/2020  9:14 AM              4 LF_Batch_2.csv
-a---           9/17/2020  9:14 AM              4 LF_Batch_10.csv
-a---           9/17/2020  9:14 AM              4 LF_Batch_20.csv
js2010
  • 23,033
  • 6
  • 64
  • 66