Locating all subdirectories matching a string or partial string

Dewi Jones picture Dewi Jones · Mar 8, 2016 · Viewed 35.4k times · Source

I basically need to set a variable to a folder path without knowing the full path.

My issue is I need to find a directory called "DirA" for example. But this directory could either be located in "DirB\" or "DirB\DirC" and sometimes the directory names that they could be contained in are not the same.

I know the first portion of the directory path will be the same regardless so i thought of using a -recurse filter to the folder name but sometimes the directory i'm looking for isn't named quite like the one that is usually expected, sometimes an extra letter on the end.

Would it be possible to do something like...

$MyVariable = Get-ChildItem D:\Data\Dir1 -Recurse | Where-Object {$_.name -like "name"} -Directory |
% { $_.fullname }

Any help is greatly appreciated!

Answer

Mark Oxley picture Mark Oxley · Mar 8, 2016

Try something like this:

$BaseDir = "C:\Dir1"
$NameToFind = "\DirA"

$MyVariable = Get-ChildItem $BaseDir -Recurse | Where-Object { $_.PSIsContainer -and $_.Name.EndsWith($NameToFind)}

This should go through all the directories in the tree, starting at C:\Dir1 and return the directory object DirA back to you.

If you only need the path of the directory, just use:

$MyVariable.FullName