views:

2066

answers:

3

How can I set an environment variable in WSH jscript file that calls another program? Here's the reduced test case:

envtest.js
----------
var oShell = WScript.CreateObject("WScript.Shell");
var oSysEnv = oShell.Environment("SYSTEM");
oSysEnv("TEST_ENV_VAR") = "TEST_VALUE";
oExec = oShell.Run("envtest.bat", 1, true);    

envtest.bat
-----------
set
pause

I expect to see TEST_ ENV _VAR in the list of variables, but it's not there. What's wrong?

edit:

If someone can produce a working code sample, I'll mark that as the correct answer. :)

A: 

You are getting the system environment variables. I suspect you simply don't have permission to modify them; you could try changing this to the user environment variables.

Also I don't know whether the argument to Environment() is case-sensitive or not. MS's documentation uses "System" instead of "SYSTEM". Might make a difference but I don't know for sure.

Joey
+2  A: 

There are 4 "collections" (System, User, Volatile, and Process) you probably want Process if you just need a child process to see the variable

Anders
+3  A: 

The problem is not in your code, but it is in execution of the process. The complete system variables are assigned to the process which is executed. so, your child process also had the same set of variables.

Your code-sample works good. It adds the variable to the SYSTEM environment.

So, you need to set the variable not only for your system but also for your process.

Here's the code.

var oShell = WScript.CreateObject("WScript.Shell");
var oSysEnv = oShell.Environment("SYSTEM");
oSysEnv("TEST1") = "TEST_VALUE";
var oSysEnv = oShell.Environment("PROCESS");
oSysEnv("TEST1") = "TEST_VALUE";
oExec = oShell.Run("envtest.bat", 1, true);  

Once you created the system variable.

It will assign the newly created variable for the current process. So, your child process can get that variable while the "SET" command executed.

Sorry for my bad-english.

Srinivasan__
Thanks !
abababa22