Batch file 变量在For循环中不回显
我正在尝试使用文件夹中的批处理文件获取文件名,但它就是不起作用 我遵循的指导原则,但出于某种原因,这是没有返回任何东西时,它应该Batch file 变量在For循环中不回显,batch-file,variables,for-loop,echo,Batch File,Variables,For Loop,Echo,我正在尝试使用文件夹中的批处理文件获取文件名,但它就是不起作用 我遵循的指导原则,但出于某种原因,这是没有返回任何东西时,它应该 FOR /F "tokens=*" %%G IN ('dir /b C:\Users\Desktop\UPD\*.txt') DO SET result=%%G 我还尝试: FOR /F "tokens=*" %%G IN (dir /b C:\Users\Desktop\UPD\*.txt') DO SET _result=%%~G echo %_result%
FOR /F "tokens=*" %%G IN ('dir /b C:\Users\Desktop\UPD\*.txt') DO SET result=%%G
我还尝试:
FOR /F "tokens=*" %%G IN (dir /b C:\Users\Desktop\UPD\*.txt') DO SET _result=%%~G
echo %_result% >> %~dp0Outputfile.txt
我得到的是:
ECHO is on.
编辑
以下是我到目前为止所做的:
IF EXIST C:\Users\Nathanael\Desktop\UPD\*.txt (
echo file found >> %~dp0Outputfile.txt
chDIR C:\Users\Nathanael\Desktop\UPD\
dir *.txt /b >> %~dp0Outputfile.txt
FOR /F "tokens=*" %%G IN ('dir /b C:\Users\Nathanael\Desktop\UPD\*.txt') DO SET result=%%G
echo %result% >> %~dp0Outputfile.txt
)
输出为:
file found
NewVHD.txt
random.txt
ECHO is on.
确保路径正确(例如,可能应该是c:\Users\YourName\Desktop\UPD*.txt
,其中YourName
是用户名)- 如果/f的
返回多个文件,则最后一个文件将覆盖
集合中的上一个文件
- 当在同一代码块中设置并使用变量时,cmd.exe解析(代码块)的方式需要延迟扩展,这与
if exist
IF NOT EXIST "C:\Users\Nathanael\Desktop\UPD\*.txt" Goto :Eof or other label
或(始终缩进代码块以更好地跟踪):
- 总是用双引号将路径括起来是一个好习惯
- 为了避免echo关闭消息,如果var可能为空,则使用空格以外的其他命令分隔符(我在这里使用了
)(
dir
命令,以确保它返回预期值。如果存在C:\Users\nathanel\Desktop\UPD*.txt(对于/F“tokens=“%%G IN('dir/b C:\Users\nathanel\Desktop\UPD\dir.txt')的回显文件找到>>%~dp0Outputfile.txt chDIR C:\Desktop\UPD*.txt')DO SET result=%%G echo%result%%>%~dp0Outputfile.txt)输出:CheckVHD started nathan file found NewVHD.txt random.txt可能的“结果”副本已作为元变量输出,%G
,因此如果您在循环中使用该元变量,而不是首先将其设置为局部变量,并在中使用该变量,作为/F%%G,则您的帖子不会出现问题(“C:\Users\nathanel\Desktop\UPD\*.txt”)可以(Echo%%G)>“%~dp0OutputFile”
。但你并不仅仅是在回显一个文件,是吗?因为你已经知道,Dir/B“C:\Users\nathanel\Desktop\UPD\*.txt”>“%~dp0OutputFile“
可以做到这一点。如果您能向我们展示您打算用%result%
做什么,这样就可以相应地定制解决方案,那就更好了。非常感谢您的解释,它工作得非常好!
IF NOT EXIST "C:\Users\Nathanael\Desktop\UPD\*.txt" Goto :Eof or other label
Setlocal EnableDelayedExpansion
IF EXIST "C:\Users\Nathanael\Desktop\UPD\*.txt" (
echo file found >> %~dp0Outputfile.txt
chDIR "C:\Users\Nathanael\Desktop\UPD\"
dir "*.txt" /b >> %~dp0Outputfile.txt
FOR /F "tokens=*" %%G IN ('dir /b C:\Users\Nathanael\Desktop\UPD\*.txt') DO SET result=%%G
echo(!result! >> %~dp0Outputfile.txt
)