首页 > 解决方案 > 将标准输出从 CD 获取到循环内的文件中

问题描述

使用我在这里找到的一些组件,我构建了一个批处理文件,以从批处理文件运行的目录开始循环遍历目录树。

批处理文件按预期工作,但我需要将 cmd.exe 命令的输出捕获CD到我在运行之前创建的文件中。

问题是如果我尝试将标准输出重定向到 .txt 文件中,我只会看到第一个找到的目录。

我发现了一些使用 PowerShell 的代码,从命令提示符屏幕中提取列表,但对我来说这是不优雅的,(虽然它似乎工作)

我已经阅读了材料,setlocal enabledelayedexpansion但它似乎高于我的工资等级,因为我无法使其工作。

工作代码如下,Rem我认为应该导出到 .txt 文件的方舟。

帮助将不胜感激。

Rem  Recursively Traverse a Directory Tree

Rem  Notes:
Rem  "For /r" command can be used to recursively visit all the directories in
Rem  a directory tree and perform a command in each subdirectory.
Rem  In this case, save the output to a text file

Rem  for /r = Loop through files (Recurse subfolders).
Rem  pushd  = Change the current directory/folder and store the previous folder/path for
Rem           use by the POPD command.
Rem  popd   = Change directory back to the path/folder most recently stored by the PUSHD
Rem           command.

@echo off
CLS
echo.
echo.
Rem  FirstJob - Generate a date and save in the work file. 

Rem Grab the date/time elements and stuff them into a couple of variables
set D=%date%
set T=%time%
set DATETIME=%D% at %T%
Rem  OK. We now have the date and time stuffed into the variable DATETIME
Rem  so now stick it into our work file along with a heading.
 Echo List of Found Directories > DirList.txt
 Echo %DATETIME% >> DirList.txt
 echo. >> DirList.txt
 echo. >> Dirlist.txt

Rem  SecondJob - Do the looping stuff and save found directories to file.

Rem  Start at the top of the tree to visit and loop though each directory
for /r %%a in (.) do (
Rem  enter the directory
 pushd %%a
 CD

Rem ------------------  direct Standard Output to the file DirList.txt -----------------

Rem  exit the directory
 popd
)

: END
Rem  All finished
Echo Done!
exit /b

在 :END 标记之前添加到上述脚本时的附加代码行。确实产生了想要的输出是:

powershell -c "$wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys('^a')
powershell -c "$wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys('^c')
powershell Get-Clipboard>>DirList.txt

标签: batch-file

解决方案


问题是你的pushd命令,因为你改变了当前目录,文件dirlist.txt必须使用绝对路径,否则你在每个pushed目录中创建它。我%~dp0这里用的是批处理文件本身的路径。

你可以试试

cd >> %~dp0\dirlist.txt

要不就

echo %%a >> %~dp0\dirlist.txt

或者您可以使用完整块的单个重定向

( 
  for /r %%a in (.) do (
    pushd %%a
    echo %%a
    popd
  )
) > dirlist.txt

推荐阅读