views:

247

answers:

2

In UNIX you can assign the output of a script to an environment variable using the technique explained here - but what is the Windows equivalent?

I have a python utility which is intended to correct an environment variable. This script simply writes a sequence of chars to stdout. For the purposes of this question, the fact that my utility is written in python is irrelevant, it's just a program that I can call from the command-prompt which outputs a single line of text.

I'd like to do something like this (that works):

set WORKSPACE=[ the output of my_util.py ]

After running this command the value of the WORKSPACE environment variable should contain the exact same text that my utility would normally print out.

Can it be done? How?


UPDATE1: Somebody at work suggested:

python util.py | set /P WORKSPACE=

In theory, that would assign the stdout of the python-script top the env-var WORKSPACE, and yet it does not work, what is going wrong here?

+4  A: 

Use:

for /f "delims=" %A in ('<insert command here>') do @set <variable name>=%A

For example:

for /f "delims=" %A in ('time /t') do @set my_env_var=%A

...will run the command "time /t" and set the env variable "my_env_var" to the result.

Remember to use %%A instead of %A if you're running this inside a .BAT file.

William Leara
Wow, that's some fugly scripting but it just might work. I'm going to try it now!
Salim Fadhley
Can you explain the meaning of %%A rather than %A in the context of a batch file?
Salim Fadhley
In batch files, "%" is a reservered character. For example, %1 refers to the first argument passed on the command line. So, in cases where you need to use a "%" where you're not referring to command line arguments, you double it up like "%%".
William Leara
This is one of the ugliest trick I often have to use. It's amazing how often in batch you have to use features intended for completely different uses to supply to the fundamental things that are missing.
Matteo Italia
Keep in mind though, that if the command has more than a single line of output you will only retain the last one in the variable.
Joey
A: 

Can I check why does my command prompt closes when i execute this line?

for /f "tokens=1 delims=: " %%A in ('call who') do set nowuser=%%A

The script is working fine on other system except one where the script exit abnormally. I debug the batch and found out this line causes the command prompt to close totally. Is there any settings i need to check for this particular system?

Many Thanks

kevin