Matthew The Terrible
Matthew The Terrible

Reputation: 1643

cmd or powershell to get all subdirectories

I'm trying to figure out what cmd or powershell command I can use to get the subdirectories contained in a directory. I only want the last subdirectory in each listed, oo for example if I have something like:

matthew\folder1\folder2\folder3

and

matthew\folder6\folder7\folder8

and I am in the "matthew" directory, I just want to return the list that has:

folder1\folder2\folder3
folder6\folder7\folder8

I try to use dir /b /s but it gives me something like:

folder1

folder1\folder2

folder1\folder2\folder3

folder6
.
.
.

Any help would be greatly appreciated.

Upvotes: 1

Views: 319

Answers (3)

MC ND
MC ND

Reputation: 70923

edited to reduce processing time

@echo off
    setlocal enableextensions disabledelayedexpansion

    subst :: .
    for /r "::\" %%a in (.) do (
        set "leaf=1"
        for /d %%b in ("%%~fa\*") do if defined leaf set "leaf="
        if defined leaf for /f "tokens=* delims=:\" %%b in ("%%~fa") do echo %%b
    )
    subst :: /d

There are two problems: determine what folders to show and remove the prefix from the output.

To solve the first problem, the folder structure under the current folder is enumerated and for each folder found it is tested if there is a folder inside. In there are no child folders, the current folder needs to be echoed.

To solve the second problem, all the operations are done under a subst drive. The current folder is defined as the root of the :: drive. That way, the full path to the current folder is removed from the string to output, replaced by a simple ::\, that will be removed with a properly configured for /f command when the folder must be echoed.

Upvotes: 2

Magoo
Magoo

Reputation: 79982

@ECHO OFF
SETLOCAL
:: Display leaves-only
SET "sourcedir=U:\sourcedir"

FOR /r "%sourcedir%" /d %%a IN (*) DO (
 SET "flag=Y"
 FOR /d %%b IN ("%%a\*") DO SET "flag="
 IF DEFINED flag ECHO %%a
 )
)


GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances.

This worked for me.

Upvotes: 0

Bacon Bits
Bacon Bits

Reputation: 32145

Still having difficulty understanding what you're looking for.

You want a list of all folders below the current folder which do not have any child folders. Additionally, you only want to display the portion of the path which is not specified by the current path.

For a Powershell answer:

Get-ChildItem -Directory -Recurse | Where-Object { 
    (Get-ChildItem $_.FullName -Directory).Count -eq 0;
} | ForEach-Object { 
    Write-Output $_.FullName.SubString((Get-Location).Path.Length);
}

Note the -Directory switch requires Powershell 3.0, if I remember right.

Upvotes: 3

Related Questions