简体   繁体   English

使用Powershell对目录名称进行排序

[英]Sort Directory name using Powershell

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

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). 由于目录的Name属性的类型为[string] ,因此将进行字母排序,该排序在9之前排在10之前(因为第一个字符1在字母9之前位于字符9之前)。

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] . 使用-as而不是-as将防止将Name属性无法转换为[int]对象发生异常。 The -as type operator is introduced in PowerShell version 3.0, so for earlier versions, use a regular cast: PowerShell版本3.0中引入了-as类型运算符,因此对于早期版本,请使用常规强制转换:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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