批处理文件"for"循环-多行 [英] Batch file 'for' loops - multiple lines

查看:654
本文介绍了批处理文件"for"循环-多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下几行在批处理文件中起作用?

Why will the following lines work in a batch file?

 for  %%a in ("C:\Test\*.txt") do set FileName=%%~a
 echo Filename is: %FileName%

但是这些不会吗?:

 for  %%a in ("C:\Test\*.txt") do (
     set FileName=%%~a
     echo Filename is: %FileName%
 )

就像"a"变量没有保留在第二行上一样.为什么会这样?如何像第二个示例一样使用"a"的内容?

It's like the "a" variable isn't retained over the second line. Why is this and how do I use the contents of "a" as in the second example?

推荐答案

这是因为括号之间的所有内容都作为一行加载.因此,%FileName%在设置之前(在运行时)已展开(在加载时).如果需要使用第二种格式,则需要启用延迟扩展.如果文件名包含!,那么您将遇到困难.如果文件名中没有括号,这将起作用.

It is because everything between the parentheses is loaded as one line. So %FileName% is expanded (at load time) before it is set (at run time). If you need to use the second format, you need to enable delayed expansion. Then you will have difficulty if the filename contains a !. This would work if there are no parentheses in filenames.

 setlocal enabledelayedexpansion
 for  %%a in ("C:\Test\*.txt") do (
     set FileName=%%~a
     echo Filename is: !FileName!
 )

这篇关于批处理文件"for"循环-多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆