In Windows shell scripting (cmd.exe) how do you as

2019-02-16 23:28发布

问题:

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?

回答1:

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.