如何迭代文件夹,以便我尊重字母(词法)顺序,但在转到旧目录的下一项之前递归到任何目录?
样本结构澄清:
Alpha |- 1.txt |- 2.txt |- 3 | |- a.txt | \- b.txt \- 4.txt Beta \- Test \- Another \- File.txt
我想以这样一种方式进行迭代:如果我要打印所有来过的项目,结果将如下所示:
Alpha 1.txt 2.txt 3 a.txt b.txt 4.txt Beta Test Another File
但是,我似乎无法弄清楚如何正确地进行递归和排序,而不用手动递归制作嵌套的Get-ChildItem
,但我希望有一种更简洁的方法,我也可以从中学习。
如果由于某种原因这太难实现,保留处理项目的顺序是对我来说重要的底线,因为如果必须的话,我可以在不保留树结构的情况下完成。
不需要手动递归,当你使用Get-ChildItem
和Sort-Object
时,Select-Object
会做你想要的。
Get-ChildItem
与Recurse获取您的项目列表sort
的FullName
将物品按照你想要的顺序排列select
Name
财产只显示项目名称得到:
Get-ChildItem C:\folder -Recurse | sort FullName | select -ExpandProperty Name
Alpha
1.txt
2.txt
3
a.txt
b.txt
4.txt
Beta
Test
Another
file.txt
可以通过简单的递归包装函数来解决:
function Get-ChildItemDepthFirst
{
param(
[Parameter(Mandatory = $true)]
[ValidateScript({Test-Path $_ -PathType Container})]
[string]$LiteralPath = $PWD
)
foreach($item in Get-ChildItem @PSBoundParameters){
# Output current item name
$item.Name
# Check to see if item is a folder, if so recurse
if($item -is [System.IO.DirectoryInfo]){
Get-ChildItemDepthFirst -LiteralPath $item.FullName
}
}
}
FWIW,我个人去找James C.'s elegant approach