写一个cmd脚本,列出指定目录下的所有子目录和文件,限制层数

发布时间 2023-09-17 11:43:18作者: yhm138

在 Windows 的 CMD shell 中,tree 命令并不直接支持指定层数。

@echo off
setlocal
set "root=%~1"
set "maxdepth=%~2"
set "curdepth=0"
set "indent="

:loop
pushd "%root%"
for /d %%D in (*) do (
    echo %indent%+-- %%D
    if %curdepth% lss %maxdepth% (
        set /a "curdepth+=1"
        set "root=%%D"
        set "indent=%indent%    "
        call :loop
        set "indent=%indent:~,-4%"
        set /a "curdepth-=1"
    )
)
popd
exit /b
tree_depth.cmd C:\path\to\directory 2