Denis Denis - 3 months ago 10
PowerShell Question

How can I find all the Grand-Parent directories where a file resides

I would like to find all the grand-parent directories where a file exists using PowerShell but can't think of how to do it. I figured I need to do something like this:

Get-ChildItem -Filter MyApp.exe -Recurse | format-table Directory


Suppose I have the file in the following places:

C:\test\AppA\201608114\MyApp.exe
C:\test\AppA\20160812a\MyApp.exe
C:\test\AppA\201608136\MyApp.exe
C:\test\AppB\201607115\MyApp.exe
C:\test\AppB\201607104\MyApp.exe
C:\test\OtherApps\AppC\201606234\MyApp.exe


So in the above example I would like Powershell to output:

C:\test\AppA
C:\test\AppB
C:\test\OtherApps\AppC


Is there a way to accomplish this in Powershell. Almost at the point of just writing a Perl/Python script for this but figured I'd give PowerShell a shot at it first

Answer

Simply get the parent of the files' directory:

Get-ChildItem -Filter MyApp.exe -Recurse | ForEach-Object {
  $_.Directory.Parent.FullName
} | Sort-Object -Unique