【问题标题】:Sorting a list of paths in Powershell在 Powershell 中对路径列表进行排序
【发布时间】:2019-04-25 02:35:54
【问题描述】:

我正在尝试对给定路径的列表进行排序(从最深的文件夹到根目录)。

有没有办法用现有的功能实现这一点?

例子:

给定:

test\A\directory1
test\B
test\A\directory1\end
test\A
test\C\directory2
test
test\C
test\directdirectory

获得:

test\C\directory2
test\A\directory1
test\directdirectory
test\C
test\B
test\A
test

【问题讨论】:

  • 您的意见是什么?只是一个 txt 文件还是其他命令的输出?
  • 你的 givenobtain 不匹配?!

标签: powershell sorting arraylist path


【解决方案1】:

您可以在排序命令中使用表达式按\ 的数量进行排序

Sort {($_ -split '\\').Count}, {$_} -Descending

示例 感谢 LotPings

@(
'test\A\directory1'
'test\B'
'test\A\directory1\end'
'test\A'
'test\C\directory2'
'test'
'test\C'
'test\directdirectory'
) | Sort {($_ -split '\\').Count}, {$_} -Descending

结果

test\A\directory1\end
test\C\directory2
test\A\directory1
test\directdirectory
test\C
test\B
test\A
test

编辑:是否对第二个必要的键进行排序 陪审团仍然没有结果

【讨论】:

  • 吹毛求疵:| Sort-Object {($_ -split '\\').Count} -Descending 具有相同的结果。 (+1)
  • @LotPings - 这取决于 OP 的需求,但我认为结果组也应该按降序排序,但也许您的意思是 shortening 解决方案,在这种情况下,谢谢。我不知道;)
  • 我确实使用PSItem 作为第二键(没有 {scriptblock})进行了测试,但输出与我的建议完全相同。
  • @LotPings - 它不适合我。如果没有明确地对第二个键进行排序,test\B 会出现在test\A 之前。也许这类似于您未指定排序顺序时数据库的工作方式:结果可以按任何顺序排列,但大多数情况下它会返回按其(索引)主键排序的结果。
猜你喜欢
  • 2011-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-25
  • 2010-10-23
  • 2021-11-06
  • 1970-01-01
相关资源
最近更新 更多