在javascript中设置环境变量
如何在调用另一个程序的 WSH jscript 文件中设置环境变量? 这是简化的测试用例:
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
我希望在变量列表中看到 TEST_ ENV _VAR,但它不在那里。 怎么了?
编辑:
如果有人可以生成工作代码示例,我会将其标记为正确答案。 :)
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. :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题不在于您的代码,而在于流程的执行。 完整的系统变量被分配给正在执行的进程。 因此,您的子进程也具有相同的变量集。
您的代码示例效果很好。 它将变量添加到系统环境中。
因此,您不仅需要为您的系统设置变量,还需要为您的进程设置变量。
这是代码。
创建系统变量后。
它将为当前进程分配新创建的变量。 因此,您的子进程可以在执行“SET”命令时获取该变量。
对不起,我的英语不好。
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.
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.
如果您只需要一个子进程来查看变量,那么有 4 个“集合”(系统、用户、易失性和进程)您可能需要 Process
There are 4 "collections" (System, User, Volatile, and Process) you probably want Process if you just need a child process to see the variable
您正在获取系统环境变量。 我怀疑你根本没有权限修改它们; 您可以尝试将其更改为用户环境变量。
我也不知道
Environment()
的参数是否区分大小写。 MS 的文档使用“System”
而不是“SYSTEM”
。 可能会有所不同,但我不确定。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.