Setting Environment Variables | Passing Vars between Apps

English support forum

Moderators: Hacker, petermad, Stefan2, white

Post Reply
User avatar
Balderstrom
Power Member
Power Member
Posts: 2148
Joined: 2005-10-11, 10:10 UTC

Setting Environment Variables | Passing Vars between Apps

Post by *Balderstrom »

I came across SetEnv.exe quite some time ago - but never used or tested it.

I recently had the need to be able to pass data between programs and found that SetEnv works fairly well in this regard.

Normally in windows we would start a CMD prompt, set some variables and then start a program from there. The newly launched program would inherit the modified command prompt's environment.

Code: Select all

::
:: Example TCLaunch.cmd
::
SET TTOOLS=%ProgramFiles%\TotalCMD\Tools
START "" "%ProgramFiles%\TotalCMD\TotalCMD.exe"
The newly launched Total Commander would now have access to the variable "TTOOLS" -- which could be used pretty much anywhere in it's interface: ButtonBar, User-Commands, TC's Command Prompt, etc.

This is all well and good, but what if you wanted to change that variable, or add more? You would need to close TC, change your TCLaunch.cmd and restart. Yet this is not the case with SetEnv.

SetEnv writes to a couple registry keys, the ones of most interest are:
[HKCU\Environment] keys/variables are permanent (for this user) until deleted, and
[HKCU\Volatile Environment] keys/variables are purged after a reboot.

Any variable/key placed into either of those locations are immediately available to all applications except for currently open command prompts. Which is one of the reasons I thought the program was of no use, as it didn't seem to consistently set any variable at all. After figuring this out I found that any Command Prompts opened afterwards will have access to the new Environment variables.

As well no new syntax is required to use them, they are accessed just like every other "normal" Environment variable, e.g. %ProgramFiles%
A slightly different syntax for the setting (or deleting) of them if you use SetEnv -- though really you could use any tool that can do registry writes.
SetEnv -v FooBar "FooBar"
SetEnv -v Foo2 "\"%ProgramFiles%\Foo\Foo.exe\""
Values with spaces require quotes, though you can just use quotes out of habit to no ill-effect. If your Value needs to contain quotes, escape them with a leading backslash.
NOTE [1]:
A variable of the same name can exist in both places, but the Volatile Key/Variable trumps the User Environment one.
SETENV -v FOOBAR "Volatile Foobar"
SETENV -u FOOBAR "User Foobar"
%FOOBAR% will return: Volatile Foobar

Though you could access both still by using SETENV syntax:
SETENV -u FOOBAR
SETENV -v FOOBAR
NOTE [2]:
If setenv.exe is placed within your %PATH%, it can be used directly from Total Commander's own command prompt -- without manually opening a standalone command prompt.
Post Reply