忽略powershell中的子目录
Ignoring subdirectories in powershell
我有一行代码可以打印出所有类似于 $filename 的文件和文件夹,例如关键字 "abc" 还将包含 file/folder "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:\_1" -Filter 'obj'
我有一行代码可以打印出所有类似于 $filename 的文件和文件夹,例如关键字 "abc" 还将包含 file/folder "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:\_1" -Filter 'obj'