简体   繁体   中英

Sort files by number in the end of a file name

I need help with a tricky task I have.

I have a list of *.xml files which have the same ending. The names below show only the naming convention rule.

EEEEEEEEEE-JJJ-ZZZZZ_DDDDD-XML--0000001629358212.xml

EEEEEEEEEE-JJJ-OOOOOO-XML--0000001533506936.xml

EEEEEEEEEE-JJJ-AAAAAA-XML--0000001572627196.xml

Filename length maybe is different but it's important for me to sort it by this number in the end. With SQL syntax it would be easier but I need a PS solution).

Sort-Object by LastWriteTime works better than other simple ways - but when it comes to a few files with the same hh:mm PS mixes the order.

At the beginning of the chains of steps that should happen with these files, I remove a time stamps from the beginning of each file name. I was able to do it with this:

dir *EEEEEEEEEE*.xml | Rename-Item -NewName {$_.name.substring($_.BaseName.IndexOf("EEEEEEEEE"))}

But I'm unable to write something similar for sorting.

Maybe someone can advise how to solve it? Maybe You have more experience with PS Substring.

Thanks in advance.

Read and follow Sort-Object , scrolling down to the -Property parameter:


The Property parameter's value can be a calculated property. To create a calculated property, use a hash table.

Valid keys for a hash table are as follows:

 expression - <string> or <script block> ascending or descending - <boolean>

For more information, see about_Calculated_Properties .

Read the Examples section as well. Use

Get-ChildItem -File -Filter "*EEEEEEEEEE*-*.xml" |
  Sort-Object -Property @{Expression = { ($_.BaseName -split '-')[-1] }}

Thank you guys for the help.

I used this line below and it worked in my case. GCI EEEEEEEEEE*.xml | Sort {$_.Name.substring($_.Name.Length - 20,14)} GCI EEEEEEEEEE*.xml | Sort {$_.Name.substring($_.Name.Length - 20,14)} It reads only the number at the end of the file name and sorts the files in the way I need.

Best regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM