我有一行代码可以打印出所有与$ filename类似的文件和文件夹,例如关键字“ abc”还将包含文件/文件夹“ abcdef”
Get-ChildItem -Path 'C:\' -Filter $filename -Recurse | %{$_.FullName}
我想让它搜索这些文件不会进入文件夹的子目录中
例如名称为“ abc”和子文件夹“ abcdef”的文件夹仅打印出“ C:\ abc”
当前代码行将打印出“ C:\ abc”和“ C:\ abc \ abcdef”
什么是最好的方法?
这将完成。
Get-ChildItem
在最高级别执行以填充处理队列($ProcessingQueue
)
然后,循环将运行,直到处理队列中没有任何元素为止。队列中的每个元素都将经历相同的过程。
要么与过滤器匹配,在这种情况下,它将被添加到$Result
变量中,否则将不被添加,在这种情况下,将在该目录上调用Get-ChildItem
,并将其结果附加到队列中。
这确保一旦我们有匹配项,就不会再处理目录树,并且仅在目录与文件夹不匹配时才应用递归。
-
Function Get-TopChildItem($Path, $Filter) {
$Results = [System.Collections.Generic.List[String]]::New()
$ProcessingQueue = [System.Collections.Queue]::new()
ForEach ($item in (Get-ChildItem -Directory $Path)) {
$ProcessingQueue.Enqueue($item.FullName)
}
While ($ProcessingQueue.Count -gt 0) {
$Item = $ProcessingQueue.Dequeue()
if ($Item -match $Filter) {
$Results.Add($Item)
}
else {
ForEach ($el in (Get-ChildItem -Path $Item -Directory)) {
$ProcessingQueue.Enqueue($el.FullName)
}
}
}
return $Results
}
#Example
Get-TopChildItem -Path "C:\_\111" -Filter 'obj'