Windows – how to set temporary environment variable windows command prompt like bash

command lineenvironment-variableswindows

In Bash I can create TEMPORARY environment variables on a command line. For eample

DEBUG=foo somecommand

This sets the environmnet variable DEBUG but only for somecommand. When the line is finished DEBUG is no longer set.

Can I do something similar in the Windows Command Processor?

Note: Using SET does not work. That sets the current command processors environment, not the just for the command about to be executed.

To give another example here's a small node.js program that prints the value
of a single environment variable

// test.js
console.log(`${process.argv[2]}='${process.env[process.argv[2]]}'`);

Let's run it in bash

$ export FOO=abc
$ node test.js FOO
FOO='abc'

Then let's run it with a temporary setting

$ FOO=def node test.js FOO
FOO='def'

Check that FOO is still abc

$ echo $FOO
abc

How I can accomplish the same thing in the Windows command prompt?

One way seems to be to relaunch the command processor as in

cmd /S /C "set "FOO=def" & node test.js FOO"

Is there another way or is that it?

Best Answer

Simply use the set command:

C:\>set foo=bar

C:\>echo %foo%
bar

C:\>exit

Open cmd again

C:\>echo %foo%
%foo%

C:\>
Related Question