对对象进行排序Sorting Objects

请考虑列出当前目录中子目录和文件的问题。如果我们想要作为排序依据LastWriteTime然后按名称,我们可以通过键入操作即可:

  1. LastWriteTime Name
  2. ------------- ----
  3. 11/6/2017 10:10:11 AM .localization-config
  4. 11/6/2017 10:10:11 AM .openpublishing.build.ps1
  5. 11/6/2017 10:10:11 AM appveyor.yml
  6. 11/6/2017 10:10:11 AM LICENSE
  7. 11/6/2017 10:10:11 AM LICENSE-CODE
  8. 11/6/2017 10:10:11 AM ThirdPartyNotices
  9. 11/6/2017 10:10:15 AM tests
  10. 6/6/2018 7:58:59 PM CONTRIBUTING.md
  11. 6/6/2018 7:58:59 PM README.md
  12. ...

您还可以进行排序的对象按相反的顺序通过指定降序开关参数。

  1. Get-ChildItem |
  2. Sort-Object -Property LastWriteTime, Name -Descending |
  3. Format-Table -Property LastWriteTime, Name
  1. LastWriteTime Name
  2. ------------- ----
  3. 12/1/2018 10:13:50 PM dsc
  4. ...
  5. 6/6/2018 7:58:59 PM README.md
  6. 11/6/2017 10:10:15 AM tests
  7. 11/6/2017 10:10:11 AM ThirdPartyNotices
  8. 11/6/2017 10:10:11 AM LICENSE-CODE
  9. 11/6/2017 10:10:11 AM LICENSE
  10. 11/6/2017 10:10:11 AM appveyor.yml
  11. 11/6/2017 10:10:11 AM .openpublishing.build.ps1
  12. 11/6/2017 10:10:11 AM .localization-config

可以通过使用哈希表数组中对不同属性进行不同的顺序进行排序。每个哈希表使用表达式键属性名称指定为字符串和一个Ascending降序键以指定排序顺序由$true$false.表达式键是必需的。升序降序关键字是可选的。

  1. LastWriteTime Name
  2. ------------- ----
  3. 12/1/2018 10:13:50 PM dsc
  4. 12/1/2018 10:13:50 PM reference
  5. 11/29/2018 6:56:01 PM .openpublishing.redirection.json
  6. 11/29/2018 6:56:01 PM gallery
  7. 11/24/2018 10:33:22 AM developer
  8. 11/20/2018 7:22:19 PM .markdownlint.json
  9. ...

您还可以设置为一个脚本块表达式密钥。运行时Sort-Objectcmdlet 执行脚本块,以及用于排序结果。

下面的示例对对象之间的时间跨度按降序进行排序CreationTimeLastWriteTime

  1. Get-ChildItem |
  2. Format-Table -Property LastWriteTime, CreationTime
  1. ------------- ------------
  2. 12/1/2018 10:13:50 PM 11/6/2017 10:10:11 AM
  3. 12/1/2018 10:13:50 PM 11/6/2017 10:10:11 AM
  4. 11/7/2018 6:52:24 PM 11/6/2017 10:10:11 AM
  5. 11/7/2018 6:52:24 PM 11/6/2017 10:10:15 AM
  6. 11/3/2018 9:58:17 AM 11/6/2017 10:10:11 AM
  7. 10/26/2018 4:50:21 PM 11/6/2017 10:10:11 AM
  8. 11/17/2018 1:10:57 PM 11/29/2017 5:48:30 PM
  9. 11/12/2018 6:29:53 PM 12/7/2017 7:57:07 PM
  10. ...

可以省略属性参数名称,如下所示:

  1. sort LastWriteTime, Name

哈希表中进行排序的键可缩写如下所示:

  1. Sort-Object @{ e = 'LastWriteTime'; d = $true }, @{ e = 'Name'; a = $true }

在此示例中, e代表表达式,则d代表降序,并代表升序

为了提高可读性,可以将哈希表放到一个单独的变量:

  1. $order = @(
  2. @{ Expression = 'LastWriteTime'; Descending = $true }
  3. @{ Expression = 'Name'; Ascending = $true }
  4. )
  5. Get-ChildItem |
  6. Sort-Object $order |