Powershell - Search for files with certain extensions that are within a specifically named folder with Child-GetChildItem

Viewed 21

I'm trying to write a Powershell Get-ChildItem command that does the following: -Within a certain directory, retrieve any file that ends with MyName.dll, but only if it is contained within a folder named "MyFolder"

For example, a path such as C:\MyRoot\FolderOne\MyFolder\FolderTwo\TestMyName.dll would be correct, and so would a path such as C:\MyRoot\MyFolder\FolderOne\FolderTwo\TestMyName.dll be. However, a path such as C:\MyRoot\FolderOne\FolderTwo\FolderThree\TestMyName.dll wouldn't be correct.

I've tried using the Filter command, which worked well to retrieve any file that ends with "MyName.dll", but I can't see how to implement a "middle filter".

Thanks a lot, any help is appreciated!

1 Answers

Filter on the entire path using Where-Object:

$folderName = 'MyFolder'
$slash = [System.IO.Path]::DirectorySeparatorChar
$intermediateFolderFilter = '*{0}{1}{0}*' -f $slash,$foldername

Get-ChildItem -LiteralPath C:\MyRoot -Recurse -Filter *MyName.dll |Where-Object FullName -like $intermediateFolderFilter
Related