Welcome to MSDN Blogs Sign in | Join | Help

System.Blog.Martens.Ben

The Tech Blog of Ben Martens
Delayed Environment Variable Expansion

Someone around the office joked that my blog is turning into "Random Batch File Tips and Tricks." I'll continue that trend with this post...

I recently encountered an environment variable surrounded by exclamation points instead of the usual percent signs. (ie. !MYENVVAR! instead of %MYENVVAR%). It turns out that this is used to delay the expansion of the environment variable until it is actually needed. The first processing step that happens in a statement is to expand all the environment variables.

I was in the process of writing up a big example when I found one on microsoft.com already. Scroll down and click on "What is delayed environment variable expansion?"

http://www.microsoft.com/technet/prodtechnol/Windows2000serv/support/FAQW2KCP.mspx

Posted: Thursday, May 10, 2007 4:17 PM by benmartens

Comments

DeborahK said:

I am setting the environment variable within an application called by the batch file. I then want to display the contents of the environment variable. Even with delayed expansion - I don't seem to be getting the current value of the environment variable - but rather the value set when the batch file is first read.

Here is my code:

CALL myApp.exe /RunSilent

echo !Test!

(Test is set within the application as a user-level environment variable.)

If I check the registry, Test always returns what is there *before* the batch file was executed, not after the myApp.exe was run.

Any tips?

# August 23, 2007 5:28 PM

no name said:

cmd.exe needs to be invoked with the /v argument.

# March 1, 2008 3:58 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker