Reputation: 35
I have a line of code that prints out all the files and folders with that are similar to $filename e.g. keyword "abc" will also include a file/folder "abcdef"
Get-ChildItem -Path 'C:\' -Filter $filename -Recurse | %{$_.FullName}
I'd like to have make it so that the search for these files does not go into the sub-directories of folders
e.g. a folder with name "abc" and subfolder "abcdef" only prints out "C:\abc"
Currently the line of code would print out "C:\abc" and "C:\abc\abcdef"
What would be the best way to do this?
Upvotes: 1
Views: 362
Reputation: 10323
This will do it.
Get-ChildItem
is performed at the top level to populate the processing queue ($ProcessingQueue
)
Then, a loop will run until the processing queue does not have any element left. Each element in the queue will undergo the same process.
Either it match the filter, in which case it will be added to the $Result
variable or it does not, in which case Get-ChildItem
will be called on that directory and its result appended to the queue.
This ensure we do not process any further a directory tree once we have a match and that that the recursion is only applied if the directory did not match the folder in the first place.
--
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'
Upvotes: 1