Search code examples
powershellsearchdirectorysubdirectory

Unable to target subfolders nested within top-level folders that may exist multiple times


I have tried numerous variations, I tried CrapGPT, I have tried combining and cobbling things and just cannot get the results I'm after.

Essentially what I'm trying to do is list all the subfolders only within top-level folder ParentFolder and then search within all subfolders for two specific folders, targetfolder1 and targetfolder2 and list all subfolders within those targeted subfolders. I then want to dump that list to a .csv.

So essentially it would look something like:

# First, list only the level 0 subfolders
Z:\ParentFolder
Z:\Parentfolder\Subfolder1
Z:\Parentfolder\Subfolder2
Z:\Parentfolder\Subfolder3
...

# Then, list all the level X subfolders that fall only within targetfolder1 and targetfolder2
Z:\Parentfolder\Subfolder1\Sub-subfolder1\targetfolder1
Z:\Parentfolder\Subfolder1\Sub-subfolder2\Sub-sub-subfolder1\targetfolder1
Z:\Parentfolder\Subfolder1\Sub-subfolder3\Sub-sub-subfolder2\targetfolder1
Z:\Parentfolder\Subfolder1\Sub-subfolder3\Sub-sub-subfolder2\targetfolder2
Z:\Parentfolder\Subfolder1\Sub-subfolder4\Sub-sub-subfolder3\sub-sub-sub-subfolder1\targetfolder1
...

So any subfolders within the Parentfolder may or may not have targetfolder1 or targetfolder2, but if they do they may or may not be at the same subfolder level as others. So if the folder name matches targetfolder1 or targetfolder2, list all and only the directories in those respective targetfolders.

Where I finally stopped was:

$parentfolder = "Z:\ParentFolder"

$results = @()
$parentfolder = Get-ChildItem -Path $folder -Depth 0 -Directory -ErrorAction SilentlyContinue
$results += $parentfolder

$targetsubfolders = Get-ChildItem $folder -Recurse | Where-Object {$_.Name -match "targetfolder1" -or $_.Name -match "targetfolder2"} | Select-Object Name
$results += $targetsubfolders

$results | Select-Object FullName | Export-Csv "C:\Users\User\Desktop\results.csv" -NoTypeInformation

I've been staring at this for so long none of it makes sense anymore. Insights are greatly appreciated.


Solution

  • Issue with your code seem to be Select-Object Name, then trying to Select-Object FullName. Those objects no longer have a .FullName property because of the previous statement. It should be removed.

    You can also leverage the pipeline here:

    $parentfolder = 'Z:\ParentFolder'
    
    # `-Depth 0` is default here, no need for it
    # get folders one level down
    Get-ChildItem -Path $parentfolder -Directory -ErrorAction SilentlyContinue |
        # get all child folders recursively
        Get-ChildItem -Directory -Recurse |
        # filter for folders where their name is 'targetfolder1' or 'targetfolder2'
        Where-Object Name -In 'targetfolder1', 'targetfolder2' |
        Select-Object FullName |
        Export-Csv 'C:\Users\User\Desktop\results.csv' -NoTypeInformation