Why will the following lines work in a batch file?
for %%a in ("C:\Test\*.txt") do set FileName=%%~a echo Filename is: %FileName%
But these won't?:
for %%a in ("C:\Test\*.txt") do ( set FileName=%%~a echo Filename is: %FileName% )
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?
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! ) endlocal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With