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.
Would escaping the % sign help? That is putting two % characters next to each other as in:
Comment by Steven Barbaglia — 2011.03.22 @ 3:23 am