Showing posts with label Batch. Show all posts
Showing posts with label Batch. Show all posts

Friday, April 3, 2009

Batch file variables modified and referenced in a for loop

More batch fun...

When a batch file executes and a loop is entered, the entire loop is parsed one time, and all variable references are expanded at that time. Supposedly this is for performance reasons, which is good because there are a lot of high-throughput batch files out there :)

So for example (from my stack overflow question):


for %%f in (%MYTARGETDIR%\*config.xml) do (
SET TMPFILE=%%F.tmp
echo In loop %TMPFILE%
)


does not show a value for the TMPFILE variable.

This can be overridden using enabedelayedexpansion:


setlocal ENABLEDELAYEDEXPANSION
for %%f in (%MYTARGETDIR%*config.xml) do (
SET TMPFILE=%%F.tmp
echo In loop !TMPFILE!
)

Thursday, March 26, 2009

How to Expand Windows Filename Globs in a Batch File

This one I needed dearly today:

In windows, filename globs like *.xml do not get expanded by the shell. Its up to each script and program to do it. Thanks for nothin' MSFT!

Here is how to do it in a batch file - a simple example, which does the equivalent of a dir command:


@echo OFF
for %%f in (%1) do (
echo %%f
)


Happy coding.