在我工作的时候,遇到了一个问题:我需要一个能够输出目录结构的工具,于是,我决定自己写一个!

@echo off
chcp 65001 > nul
setlocal enabledelayedexpansion

REM 获取当前脚本所在目录的绝对路径
for %%F in ("%~dp0.") do set "current_dir=%%~fF"

REM 设置输出文件的路径
set "output_file=%current_dir%\directory_structure.md"

REM 清空输出文件
type nul > "%output_file%"

REM 输出目录结构
echo ``` >> "%output_file%"
call :traverse "%current_dir%" "" "%output_file%"
echo ``` >> "%output_file%"

REM 完成提示
echo 目录结构已输出到 %output_file%
pause
exit

:traverse
set "folder=%~1"
set "indent=%~2"
set "output_file=%~3"

REM 获取当前目录的相对路径
set "relative_path=!folder:%current_dir%=!"

REM 输出当前目录的标题
echo %indent%── !relative_path! >> "%output_file%"

REM 遍历当前目录下的文件和子目录
set "sub_indent=%indent%   "
for /f "delims=" %%F in ('dir /b /a-d "%folder%"') do (
    echo %sub_indent%├── %%F >> "%output_file%"
)

for /f "delims=" %%D in ('dir /b /ad "%folder%"') do (
    call :traverse "%folder%\%%D" "%sub_indent%│" "%output_file%"
)

exit /b