Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Sort-Object Name with numbers doesn't properly

I am trying to find .sql files in a folder and filtering them based on the last write time. Based on the last write time I got 4 files as output.

TestScript10.sql
TestScript5.sql
TestScript6.sql
TestScript7.sql

Now when my command tries to do sort-object I am seeing Testscript10 at the top instead of TestScript5, how do I fix this issue?

My Code

$File= Get-ChildItem $FileLocation -Filter *.sql | Where-Object {$_.LastWriteTime -gt $datetime} | Sort-Object Name

$File Output

[DBG]: PS SQLSERVER:\>> $File


    Directory: C:\SQLScripts


Mode                LastWriteTime     Length    Name
----                -------------     ------ ----
-a---         5/22/2014  10:20 AM         61 TestScript10.sql
-a---         5/22/2014  10:16 AM         60 TestScript5.sql
-a---         5/22/2014  10:24 AM         66 TestScript6.sql
-a---         5/22/2014  10:10 AM         24 Testscript7.sql
like image 703
user3618372 Avatar asked Nov 30 '22 19:11

user3618372


2 Answers

Thanks for all your suggestions above for my question. After streamlining the suggestions, the code below worked well for my situation. This is helping me sort in the natural order like Windows Explorer does.

$ToNatural= { [regex]::Replace($_, '\d+',{$args[0].Value.Padleft(20)})}
$File= Get-ChildItem $FileLocation -Filter *.sql | Where-Object {$_.LastWriteTime -gt $datetime} | Sort-Object $ToNatural
like image 66
user3618372 Avatar answered Dec 05 '22 06:12

user3618372


Something like this:

| sort-object {[int]($_.basename -replace '\D')}
like image 29
mjolinor Avatar answered Dec 05 '22 06:12

mjolinor