1
votes

I'm able to recursively search a directory using Get-ChildItem -Recurse to locate a particular directory, but I'm only interested in the case where the directory is a child of another specific directory. The parent/child may exist at any arbitrary depth in the directory tree. For instance:

C:\lev1\lev2\lev3\lev4\parentDir\childDirToFind\lev7...

The following code returns all occurrences of childDirToFind :

Get-ChildItem -Path C:\\*\\*\ChildDirToFind -Recurse

I've tried including the parentDir in the -Path option and get no results; e.g.:

Get-ChildItem -Path C:\\*\\*\parentDir\childDirToFind -Recurse

I've also tried to use the -Filter option with no results. Perhaps Get-ChildItem isn't the best approach? Ideally, I'd like Get-ChildItem to return immediately after finding the directory and not continue searching the entire tree.

2
try Get-ChildItem -Path c:\ -Recurse -Filter childDirToFindKory Gill
With aliases: gci x:\start -dir -rec -filter childDirToFind |? {$_.Parent.Name -eq 'parentDir'} | select -first 1user6811411
BTW, as the search should stop with the first find a trailing \lev7.. isn't possible.user6811411

2 Answers

1
votes

Here's an example where parent is drivers and child is etc

Get-ChildItem C:\Windows -Recurse -Directory -ErrorAction SilentlyContinue | ? { $_.FullName -like '*\drivers\etc' }

I added the -ErrorAction parameter to hide all the inaccessible folder errors.

0
votes

Thanks to Rich Moss and LotPings for steering me in the right direction. Both solutions provide the correct results although piping the output to "select -first 1" does have the added benefit of stopping the directory search once the result is found. I'm not sure why, but using -filter and comparing $.Parent.Name is twice as fast as comparing $.FullName (as checked using Measure-Command). I ultimately went with this:

cgi C:\ -dir -rec -ea SilentlyContinue -filter childDirectory | ? {$_.Parent.Name -eq 'parentDir'} | select -first 1