batch-file - 将标准输出从 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
解决方案
问题是你的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
推荐阅读
- html - JQuery - 从其可滚动区域取消链接可拖动元素
- javascript - removeAttribute 不适用于数组中的最后一个元素
- machine-learning - 如何交叉验证具有比 sklearn 中的类更多的集群的 KMeans?
- mysql - 使用查询将多个 excel 文件摄取到 MySQL
- email - 电子邮件线程/链如何工作,我如何确保分别发送两封电子邮件将在用户电子邮件客户端的一个线程中合并在一起?
- sql-server - 从 varchar 转换为十进制而不损失精度
- php - 如何让 laravel 工厂检查索引约束
- ios - Appcelerator 钛金属上的垂直滚动滞后
- python - 尝试在 Selenium Python 中的标签后获取信息
- mysql - phpmyadmin 5.0.1 中的注意事项:尝试访问 bool 类型值的数组偏移量,在设计器模式下注意