1

As stated here Is it possible to set an environment variable to the output of a command in cmd.exe I always used that

mycommand.exe>%TEMP%\out.txt
set /P FOO=<%TEMP%\out.txt

But that's ugly because it creates a file.

The for method is better but complicated

I wanted something simple a la unix, like:

mycommand.exe|set /P FOO=

No error, but FOO is not set after I run that.

Why is this not working?

Community
  • 1
  • 1
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • See the explanation at [this post](http://stackoverflow.com/questions/8192318/why-does-delayed-expansion-fail-when-inside-a-piped-block-of-code/) – Aacini Aug 02 '16 at 18:03

1 Answers1

2

Best way I can think of doing this would be to create your own little batch file that silently uses the FOR construct. For instance, you could create a batch named BatchSet.bat, stored somewhere on your path. The batch would contain the following code:

@Echo off
for /f "delims=" %%i in ('%2') do set %1=%%i
Set %1

If you run this with the following command:

BatchSet MyVar whoami

You'll get something like:

MyVar=servername\John

Obviously, the command you run should limit its output to a single line to be stored properly in the environment variable. For instance, if you run it like this:

BatchSet MyVar Vol

Then you'll only get the first line of the Vol command's output

MyVar= Volume on drive C is labeled MyDisk

But all in all, it's a fairly elegant way of doing what you were looking for.

Note that the last line in the batch is simply there to provide visual output. It can be removed altogether.

Filipus
  • 520
  • 4
  • 12
  • 1
    You may use an equal-sign as separator in the parameters of the Batch file. Also, don't forget to include the `call` command when this Batch file is used in another one: `call BatchSet MyVar=whoami` – Aacini Aug 04 '16 at 14:20