Setting multiple environment variables in a shell spawned via windows batch script

6

2

I have a batch file that spawns a shell with a modified path with the following command:

cmd /K set PATH=%PATH%;<additional path locations>

I want to set additional environment variables for the spawned shell as well. Is there any way to do that?

quanticle

Posted 2009-08-15T00:42:57.110

Reputation: 744

Answers

2

Simply add another variable on a new line using set as shown in your example. You will also want to remove the /K switch from the first line as execution will stop after that line.

set NEWVAR=SOMETHING

will create a new variable called NEWVAR with the value SOMETHING. If you wish to keep the same behavior and keep cmd open with the /K switch just put it at the end.

example:

set PATH=%PATH%;C:\Folder;
set NEWVAR=SOMETHING
echo %NEWVAR%

John T

Posted 2009-08-15T00:42:57.110

Reputation: 149 037

1Thanks - that worked like I wanted it to. I put cmd /K at the end because I wanted to use the shell after it had finished executing my commands. – quanticle – 2009-08-15T01:10:22.353

2You can also write a batch that makes all necessary changes to the environment and then simply start your cmd instance with cmd /k setvars.cmd. This is for example how Visual Studio sets up its command prompt. – Joey – 2009-08-15T12:26:13.707

1

You could also combine them into a single line as follows:

set A=foo & B=bar & C=baz

This way, you could avoid having to modify the original script and run it like so:

set A=foo & B=bar & C=baz & c:\path\to\foo.bat

Matthew Fellows

Posted 2009-08-15T00:42:57.110

Reputation: 111

1When running this from an npm/yarn script, I had to prefix each variable assignment with set. e.g. set A=foo & set B=bar & set C=baz & c:\path\... – Greg K – 2019-01-16T18:02:00.957