1

我想创建一个批处理文件。当它被调用为batch.bat MyProjectorbatch.bat MyProject/时,它将产生以下列表。请注意,这DirMyProject. 我正在使用 Windows 7。

Dir
Dir/SubDir1
Dir/SubDir1/SubSubDir1
Dir/SubDir1/SubSubDir2
Dir/SubDir2
Dir/SubDir2/SubSubDir1
Dir/SubDir2/SubSubDir2
Dir/SubDir2/SubSubDir3
Dir/SubDir3
Dir/SubDir4

如何将目录树列表写入文本文件?

必须排除文件名。

4

2 回答 2

2

好的 - 这应该这样做。它需要一个参数(根文件夹)。

@ECHO OFF

SET root=%1

REM Get the length of the root, to make the path relative later.
REM See http://stackoverflow.com/questions/5837418/how-do-you-get-the-string-length-in-a-batch-file.
ECHO %root%>x&FOR %%? IN (x) DO SET /A rootlength=%%~z? - 1&del x 

for /F "tokens=*" %%G in ('DIR %1 /AD /S /B') do (
    CALL :PrintDirectory "%%G" %rootlength%
)

GOTO :eof

:PrintDirectory 
REM %1 Path to the folder
REM %2 Length of root string.

REM See http://www.dostips.com/DtTipsStringManipulation.php#Snippets.LeftString for
REM information on the string manipulation.

@ECHO OFF
SET start=%2
SET absPath=%1

REM Remove the path root by taking the right-hand side of the string.
CALL SET relPath=%%absPath:~%start%,-1%%

ECHO.%relPath%

您可以通过将结果重定向到批处理文件来执行它:

PrintDirectoryStructure.bat c:\MyProject > out.txt
于 2012-08-07T08:21:37.410 回答
2

FORFILES 提供了一个简单的解决方案,但它是SLOW。该命令在批处理文件或命令行中同样有效:

forfiles /s /p "c:\MyProject" /m * /c "cmd /v:on /c if @isdir==TRUE (set f=@relpath&echo !f:~3,-1!)" >listing.txt

如果以 MyProject 作为当前目录运行命令,则可以
/p "c:\MyProject"从命令中删除该选项。

如果您不介意将相对路径括在.\每个路径前面的引号中,那么解决方案会更简单:

forfiles /s /p "c:\MyProject" /m * /c "cmd /c if @isdir==TRUE echo @relpath" >listing.txt
于 2012-08-07T11:53:10.157 回答