试图自学:当处理一整棵树的项目时
get-childitem -recurse
我经常必须从叶级到顶层进行(例如,删除文件和文件夹,修改树的上层然后尝试处理下层是有问题的。
为了解决这个问题,我已经通过路径中的分隔符数量对整个集合进行排序,首先获取叶级别,然后是树的上层:
$someFiles = Get-ChildItem -Recurse |
Sort @{Expression={ ( $_.fullname | select-string "\\" -AllMatches ).matches.count };
Descending=$true }
这感觉不对 - 我的编码经验有限,但我知道如果我只是以正确的方式遍历树,这种昂贵且愚蠢的排序应该是不必要的。但是 -recurse 非常方便!
什么是更聪明的方法来做到这一点?具体来说,有没有一种方法可以使用 get-childitem 从叶子向上遍历树,而不需要对所有结果进行排序?
您可以避免使用正则表达式而只使用字符串拆分方法。它的性能也更好。
dir -recurse | sort -Property @{ Expression = {$_.FullName.Split('\').Count} } -Desc
Run Code Online (Sandbox Code Playgroud)
结果:
TotalMilliseconds : 346.1253
Run Code Online (Sandbox Code Playgroud)
对...
Get-ChildItem -Recurse | Sort @{Expression={ ( $_.fullname | select-string "\\" -AllMatches ).matches.count }; Descending=$true }
Run Code Online (Sandbox Code Playgroud)
结果:
TotalMilliseconds : 953.6606
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3825 次 |
| 最近记录: |