我们可以组织显示的数据,以便更轻松地使用 Sort-Object cmdlet 进行扫描。
Sort-Object 采用一个或多个属性的名称进行排序,并返回按这些属性的值排序的数据。
基本排序
请考虑列出当前目录中的子目录和文件的问题。 如果要按 LastWriteTime 排序,然后按 名称排序,可以通过键入以下内容来执行此操作:
Get-ChildItem |
Sort-Object -Property LastWriteTime, Name |
Format-Table -Property LastWriteTime, Name
LastWriteTime Name
------------- ----
11/6/2017 10:10:11 AM .localization-config
11/6/2017 10:10:11 AM .openpublishing.build.ps1
11/6/2017 10:10:11 AM appveyor.yml
11/6/2017 10:10:11 AM LICENSE
11/6/2017 10:10:11 AM LICENSE-CODE
11/6/2017 10:10:11 AM ThirdPartyNotices
11/6/2017 10:10:15 AM tests
6/6/2018 7:58:59 PM CONTRIBUTING.md
6/6/2018 7:58:59 PM README.md
...
还可以通过指定 降序[switch] 参数以相反的顺序对对象进行排序。
Get-ChildItem |
Sort-Object -Property LastWriteTime, Name -Descending |
Format-Table -Property LastWriteTime, Name
LastWriteTime Name
------------- ----
12/1/2018 10:13:50 PM reference
12/1/2018 10:13:50 PM dsc
...
6/6/2018 7:58:59 PM README.md
6/6/2018 7:58:59 PM CONTRIBUTING.md
11/6/2017 10:10:15 AM tests
11/6/2017 10:10:11 AM ThirdPartyNotices
11/6/2017 10:10:11 AM LICENSE-CODE
11/6/2017 10:10:11 AM LICENSE
11/6/2017 10:10:11 AM appveyor.yml
11/6/2017 10:10:11 AM .openpublishing.build.ps1
11/6/2017 10:10:11 AM .localization-config
使用哈希表
可以使用数组中的哈希表按不同的顺序对不同的属性进行排序。 每个哈希表都使用表达式键将属性名称指定为字符串,并使用升序或降序键指定排序顺序$true$false。
表达式键是必需的。
升序或降序键是可选的。
下面的示例按 LastWriteTime 顺序降序和升序 名称 顺序对对象进行排序。
Get-ChildItem |
Sort-Object -Property @{ Expression = 'LastWriteTime'; Descending = $true },
@{ Expression = 'Name'; Ascending = $true } |
Format-Table -Property LastWriteTime, Name
LastWriteTime Name
------------- ----
12/1/2018 10:13:50 PM dsc
12/1/2018 10:13:50 PM reference
11/29/2018 6:56:01 PM .openpublishing.redirection.json
11/29/2018 6:56:01 PM gallery
11/24/2018 10:33:22 AM developer
11/20/2018 7:22:19 PM .markdownlint.json
...
还可以将脚本块设置为 表达式 键。 运行 Sort-Object cmdlet 时,将执行脚本块,并使用其结果进行排序。
以下示例按 CreationTime 和 LastWriteTime 之间的时间跨度按降序对对象进行排序。
Get-ChildItem |
Sort-Object -Property @{ Exp = { $_.LastWriteTime - $_.CreationTime }; Desc = $true } |
Format-Table -Property LastWriteTime, CreationTime
LastWriteTime CreationTime
------------- ------------
12/1/2018 10:13:50 PM 11/6/2017 10:10:11 AM
12/1/2018 10:13:50 PM 11/6/2017 10:10:11 AM
11/7/2018 6:52:24 PM 11/6/2017 10:10:11 AM
11/7/2018 6:52:24 PM 11/6/2017 10:10:15 AM
11/3/2018 9:58:17 AM 11/6/2017 10:10:11 AM
10/26/2018 4:50:21 PM 11/6/2017 10:10:11 AM
11/17/2018 1:10:57 PM 11/29/2017 5:48:30 PM
11/12/2018 6:29:53 PM 12/7/2017 7:57:07 PM
...
提示
可以省略 属性 参数名称,如下所示:
Sort-Object LastWriteTime, Name
此外,还可以按其内置别名引用Sort-Object: sort
sort LastWriteTime, Name
哈希表中用于排序的键可以缩写如下:
Sort-Object @{ e = 'LastWriteTime'; d = $true }, @{ e = 'Name'; a = $true }
在此示例中,e 表示表达式,d 表示降序,a 表示升序。
若要提高可读性,可以将哈希表放入单独的变量中:
$order = @(
@{ Expression = 'LastWriteTime'; Descending = $true }
@{ Expression = 'Name'; Ascending = $true }
)
Get-ChildItem |
Sort-Object $order |
Format-Table LastWriteTime, Name