Setting an environment variable in javascript
Asked Answered
G

3

6

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. :)

Grania answered 20/4, 2009 at 14:21 Comment(1)
I wonder if you are trying to do something malicious.Ingot
N
7

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.

Nor answered 2/6, 2009 at 5:59 Comment(1)
I opened another question to ask if something like that can be used to retrieve the environment variable value, do you know something about?Irvin
O
2

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

Opportunism answered 12/5, 2009 at 15:59 Comment(0)
F
0

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.

Forepeak answered 21/4, 2009 at 6:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.