views:

1170

answers:

3

Is it possible to make a batch file which can make a persistent change to an environment variable?

For example my installer.bat script copies some files to a random location in the computer's file-system. I'd like to add that location to the PATH environment variable so that the programs can be run in the current session.

FYI - the stuff I am installing changes very frequently: I want to do a fresh install every single time I run the program. Also, I do not want to over-write other previously installed copies of the program just in case some other (older) instance is still executing.

I'd like to be able to do something like this:

rem install_and_run.bat
install.bat 
myapplication.exe

Unfortunately this does not work, because the install.bat never "returns" to the main-script. myapplication.exe is never called. Next I tried:

cmd /C install.bat
myapplication.exe

Unfortunately this does not work because it means that install.bat is run in an entirely seperate cmd.exe shell. That means none of the environment variable changes persist once the script terminates because the cmd.exe also terminates.

There must be a way to make a batch-file which changes environment variables

Any suggestions?

+1  A: 

well, you could do:

Set EnvVariableName="Some Value"

as to your calling a seperate batch file from within another batch file, I believe the call command will return

rem install_and_run.bat
call install.bat
myapplication.exe

cbeuker
+6  A: 

In your case, what you want is

rem install_and_run.bat
call install.bat 
myapplication.exe

That is, use call to call install.bat, so that control will return to install_and_run.bat.

I think you don't understand that environment variables are per-process. Your batch file is running in an instance of cmd.exe, and that instance has an environment. When you wrote cmd /C you were creating a new instance of cmd.exe, which has its own environment. Then install.bat was making a "persistent" change to the environment of the new instance of cmd.exe.

Jay Bazuzi
+1  A: 

You can't create or modify an environment variable and have it persist between console sessions from a batch script, AFAIK.

I have a VBScript script with a batch script wrapper that I use for this, but I think Jay has the correct solution for you. If you like though, I can post my code.

Patrick Cuff