pankal
pankal

Reputation: 124

Order of numbered files by get-childitem

I need to change the order by which get-childitem returns the filenames in a directory because it is important to process them in a specific way. The filenames have the following format: f_1.csv, f_2.csv, f_3.csv, f_4.csv, ... , f_10.csv, f_11.csv e.t.c. The default order that are returned by get-childitem are: f_1.csv, f_10.csv, f_100.csv.

One solution would be to change the filenames to f_001.csv, f_002.csv, f_003.csv but I have no control on how the files were created and I do not know their number (may be hundreds, thousands e.t.c.)

My current code is:

    foreach($file in Get-ChildItem $path -Filter f_*.csv) 
    {
        #process the files here
    }

Thank you

Upvotes: 0

Views: 820

Answers (1)

mjolinor
mjolinor

Reputation: 68331

Something like this?

Get-ChildItem -Filter f_*.csv |
 sort @{Expression={[int]($_.name -replace 'f_(\d+).+','$1')};Descending=$false}

Upvotes: 3

Related Questions