Search code examples
powershellsubdirectory

How do I get the names of certain subfolders that only contain files and no other subfolders?


From a folder with subfolders several levels deep, I want to save only the subfolder names (without path) to a text file containing only files and no more subfolders.

Example: Only the subfolder "Test" which is located in C:\1\2\3 contains files but no further subfolders. The script should detect this and save the folder name Test in a text file. If there are more subfolders like "Test", these should also be saved in the text file.

The main folder with the subfolders should be the folder that is on the same folder level as the .ps1 file.

How can I realize this?


Solution

  • Start by finding all folders and subfolders (recursively) in the current path:

    Get-ChildItem -LiteralPath $PSScriptRoot -Directory -Recurse
    

    Then filter based on whether each directory itself contains 0 subfolders and more than 0 files:

    Get-ChildItem -LiteralPath $PSScriptRoot -Directory -Recurse |Where-Object {
      -not($_ |Get-ChildItem -Directory |Select-Object -First 1) -and $($_ |Get-ChildItem -File -Filter *.txt |Select-Object -First 1)
    }
    

    If $_ |Get-ChildItem -Directory |Select-Object -First 1 returns anything, then it means there's at least 1 subfolder.

    Similarly, if $_ |Get-ChildItem -Filter *.txt |Select-Object -First 1 returns anything, then we know at least 1 .txt file exists in the directory.

    Then we just need to get the folder name, which you can grab with Select-Object -ExpandProperty or ForEach-Object:

    Get-ChildItem -LiteralPath $PSScriptRoot -Directory -Recurse |Where-Object {
      -not($_ |Get-ChildItem -Directory |Select-Object -First 1) -and ($_ |Get-ChildItem -File -Filter *.txt |Select-Object -First 1)
    } |Select-Object -ExpandProperty Name