1

I have a folder that contains sub-folders for each application version(decimal number). Now, I have a powershell script for version comparison. The problem is I can't sort it as expected. How can I solve it in one line code, because I am doing it from batch script.

Using Get-ChildItem to see folder content

Current sort(executing from batch script:

powershell -Command "& {Get-ChildItem "\folder_dir\" -Name | sort-object -descending }

Options for solution:

  1. Sort Get-ChildItem by date, and somehow print only the names of the folders(without the title "Name" like as in regular output)
  2. Sort Get-ChildItem by name, and somehow to sort it(the problem is with decimal numbers)

For example(descending or ascending, doesn't matter. The order is what is matter):

Folder content:
1.0
1.111
1.11
2.2
1.18
2.5
2.44

Current output:
2.5 <-- wrong place
2.44
2.2
1.18 <-- wrong place
1.111
1.11
1.0

Expected sort:
1.0
1.11
1.18
1.111
2.2
2.5
2.44
  • Closest answer was in link. But I don't have letters, only numbers – igor Nov 7 '17 at 11:58
  • 2
    What you're looking for is natural sorting. This or this might be helpful. As for your example why would you not be able to adapt it? It's just that you would split using the dot and sort each group? – Seth Nov 7 '17 at 13:15
  • Convoluted but it matches your sample: Get-ChildItem "\folder_dir\" -Name | sort $("{0}.{1}" -f ($_ -replace '^(.*?)\.\d+$', '$1'), ($_ -replace '^.*?\.(\d+)$', '$1').PadLeft(10, "0")) – Lieven Keersmaekers Nov 7 '17 at 13:17
  • @Seth 's nartual sorting example works. – root Nov 7 '17 at 13:18
  • @Seth solution worked. Final command: powershell -Command "& {Get-ChildItem "\\nas\shared\Public\Igor\gscript\version" -Name | sort-object { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20) }) }} – igor Nov 7 '17 at 13:24
1

Credit to @Seth solution

From link

Final command: powershell -Command "& {Get-ChildItem "\\nas\shared\Public\Igor\gscript\version" -Name | sort-object { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20) }) }}

0

Your script is working perfectly.

You have sort in descending order, and that is exactly what it does.

Notice that the number on the left of the . also goes from high to low.

So your script would need to be as follows:

powershell -Command "& {Get-ChildItem "\\nas\shared\Public\Igor\gscript\version" 
   -Name | sort-object }

Sort-Object sorts in ascending order by default unless -descending is used.

  • (1)There is no "ascending" for sort-object in ps (2)My script doesn't work properly, look at the description – igor Nov 7 '17 at 12:09
  • @igor my bad. It does ascending by default, unless you set -descending. Edited my answer to reflect. – LPChip Nov 7 '17 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.