Nothing and Everything

2010.11.18

Windows CMD parsing, preventing environment variable expansion inside quoted string

Filed under: Programming — kevenker @ 3:45 pm

I have a console-based app that talks to a database. I wanted to set a particular field value to be the environment variable, not the value of the envrionment variable. For example:

myapp -setdbvalue "User %USERNAME% is on %COMPUTERNAME%."

So the string I want stored in the database is “User %USERNAME% is on %COMPUTERNAME%.”.

However, if you call the above, you would end up with a string like: “User KEVENKER is on KILOTWO.” Definitely NOT the intended value. :)

After about an hour of searching, I never found the definitive answer! However, I learned enough from reading http://stackoverflow.com posts and http://ss64.com/nt/ that I managed to come up with this solution:

myapp -setdbvalue "User "%"USERNAME% is on "%"COMPUTERNAME%."

So what happens here is that the cmd processer sees the following strings:

"User " + "%" + "USERNAME% is on " + "%" + "COMPUTERNAME%."

and simply concatenates these all together into one string when passing this argument to my program.

So there you have it. I hope this helps some hapless person. Hopefully the title will be good enough for searching. I’m sure this has been solved before but finding the solution is the hard part. :)

Advertisement

1 Comment »

  1. Would escaping the % sign help? That is putting two % characters next to each other as in:

    myapp -setdbvalue "User %%USERNAME%% is on %%COMPUTERNAMER%%."
    

    Comment by Steven Barbaglia — 2011.03.22 @ 3:23 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.