2012-08-07 35 views
1

我想创建一个批处理文件。当它被调用为batch.bat MyProjectbatch.bat MyProject/时,它将产生以下列表。请注意0​​是MyProject的子目录。我正在使用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 

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

必须排除文件名。

+0

这是否有批办?例如,在Powershell中这将非常简单,但在批处理中非常困难。 – 2012-08-07 07:47:01

+0

是的。仅在批处理文件中,为了简单和兼容性。 – 2012-08-07 07:48:36

+0

你可以调用VBScript吗?再次,这将使事情变得极其简单... – 2012-08-07 08:04:26

回答

2

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

forfiles /s /p "c:\MyProject" /m * /c "cmd /v:on /c if @isdir==TRUE (set [email protected]&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 
+0

值得注意的是,在当前版本中,它将'listing.txt'放入**用户主目录**(即Windows 7中的'C:\ Users \ [用户名]',可能还有其他)。我很惊讶,因为我首先查看'c:'中的'listing.txt'和文件夹,我想转储哪个结构。 – trejder 2014-06-01 10:02:17

+0

@trejder - 正如所写,它将在控制台的当前目录中创建文件。您可以在重定向中包含路径,也可以在重定向的FORFILES命令之前使用CD或PUSHD。 – dbenham 2014-06-01 13:33:47

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 
+0

我测试过它,但有些路径丢失。你测试过了吗? – 2012-08-07 08:41:32

+0

@GarbageCollector我发现了一个会导致问题的错误,如果路径中有空格。这现在已经被修正了(注意我添加的''tokens = *“'文本)。现在对你有用吗?如果没有,请给出关于哪些文件夹没有看到的更多细节... – 2012-08-07 09:42:36

+0

当我在c:\ users \ Garbage Collector \“'产生'output.txt文件时调用'PrintDirectoryStructure.bat downloads> output.txt' '只有一个项目,即使我的'downloads'包含很多目录。 – 2012-08-07 09:47:35