8

I have list of directories. Directories are named as numbers. How to sort the directory name in numeric order by power shell.

Name
-----
1
12
2
2

1 Answer 1

11

The sort order is based on the type of the property being used for comparison.

Since the Name property of your directories are of type [string], alphabetical sorting takes place, which ranks 10 before 9 (because the first character 1 precedes the character 9 in alphabetical order).

To sort the numbers by numeric value, use a scriptblock (as shown in the comments) or a calculated expression to cast the value to a numeric type:

Get-ChildItem -Directory | Sort-Object -Property {$_.Name -as [int]}

Using -as, rather than a cast will prevent exceptions for objects where the Name property cannot be converted to [int]. The -as type operator is introduced in PowerShell version 3.0, so for earlier versions, use a regular cast:

Get-ChildItem -Directory | Sort-Object -Property {[int]$_.Name}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.