一个简单的解决方案是使用robocopy 命令。虽然用于文件复制操作,但它包含一个/L 开关,用于请求不复制但要列出。调整开关以删除您可以使用的不需要的信息
robocopy . . /e /nfl /njh /njs /ns /lev:4 /l
这将递归(/e)列出(/l)当前文件夹下的所有选定元素,不显示文件信息(/nfl),没有作业标题(/njh),没有摘要(/njs ),没有文件/大小计数器 (/ns) 用于深度搜索四个级别(当前文件夹加上下面三个所需级别)
robocopy 命令的输出在行首包含一些制表符/空格。如果你需要删除它们,你可以使用类似的东西
for /f "tokens=*" %a in ('robocopy . . /e /nfl /njh /njs /ns /lev:4 /l') do echo %a
或者,从批处理文件中
for /f "tokens=*" %%a in ('robocopy . . /e /nfl /njh /njs /ns /lev:4 /l') do echo %%a
已编辑如果robocopy 的使用有问题(在您的系统中不可用/不允许),或者您需要(来自 cmets)将输出限制为仅最后一个级别,您可以使用一些东西喜欢
@echo off
setlocal enableextensions disabledelayedexpansion
rem Retrieve folder from command line, default current folder
for /f "delims=" %%a in ("%~f1\.") do set "target=%%~fa"
echo ----------------------------------------------------------------------
rem Call subroutine searching for ALL folders up to 3 levels
call :treeDump target 3
echo ----------------------------------------------------------------------
rem Call subroutine searching for folders ONLY 3 levels deep
call :treeDump target 3 true
goto :eof
rem Recursive folder search
:treeDump targetVar maxLevel forceLevel
rem targetVar = name of variable containing the folder to iterate
rem maxLevel = how many levels to search under target
rem forceLevel = only show the last requested level
setlocal disabledelayedexpansion
rem Check we are not searching too deep
2>nul set /a "nextLevel=%~2-1", "1/(%~2+1)" || goto :eof
rem Retrieve folder to iterate
setlocal enabledelayedexpansion & for %%a in ("!%~1!") do endlocal & (
rem Determine if current level must be shown
if "%~3"=="" (
echo %%~fa
) else (
if %nextLevel% lss 0 echo %%~fa
)
rem If not at the last level, keep searching
if %nextLevel% geq 0 for /d %%b in ("%%~fa\*") do (
set "target=%%~fb"
call :treeDump target %nextLevel% "%~3"
)
)
goto :eof
它使用递归函数来遍历目录树。对于找到的每个文件夹,如果我们不在所需的级别,则会枚举子文件夹并为每个文件夹再次调用该函数。