可执行文件如何在父CMD或批处理上下文中设置环境变量? [英] How can an executable set an environment variable in the parent CMD or batch context?

查看:208
本文介绍了可执行文件如何在父CMD或批处理上下文中设置环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Windows控制台可执行文件(称为SetEnvX.exe),用于设置环境变量.内部调用 SetEnvironmentVariable 在Windows API中.该呼叫成功.

I have a Windows console executable (call it SetEnvX.exe) that sets an environment variable. Internally it calls SetEnvironmentVariable in the Windows API. That call succeeds.

在执行SetEnvX.exe的父CMD实例中,如果在SetEnvX.exe之后立即运行SET,则它创建的环境变量不存在.

In the parent CMD instance that executes SetEnvX.exe, the environment variable it created does not exist if SET is run right after SetEnvX.exe.

如果我用行创建一个TEST.CMD

If I create a TEST.CMD with the lines

SetEnvX.exe
set

TEST.CMD中SET命令的输出也未显示由SetEnvX.exe创建的环境变量.

the output of the SET command within TEST.CMD also does not show the environment variable created by SetEnvX.exe.

诸如SetEnvX.exe之类的程序如何创建一个环境变量,该环境变量存在于执行该交互变量的交互式CMD Shell或批处理文件的范围内?换句话说,我不想将环境变量放入全局的持久性环境中.

How can a program such as SetEnvX.exe create an environment variable that exists for the scope of the interactive CMD shell or batch file from which it was executed? In other words, I do not want to put the environment variable into the global, persistent environment.

推荐答案

这是不可能的.每当调用SetEnvX.exe时,cmd.exe都会生成一个子进程,该子进程将从cmd.exe继承环境变量.

This is not possible. Whenever you call SetEnvX.exe cmd.exe spawns a child process which inherits environment variables from cmd.exe.

SetEnvX.exe在其环境中设置环境变量,但是完成后,它的环境块消失了.因此父cmd.exe不会从子SetEnvX.exe获取任何变量.

SetEnvX.exe sets the environment variable in its environment but when it finishes, it's environment block disappears. So parent cmd.exe does not get any variables from child SetEnvX.exe.

TL; DR:

子进程可以继承父级的环境变量,但是父进程退出时不能继承子级的环境变量.

Child process can inherit parent's environment variables but parent cannot inherit child's environment variables when it exits.

解决方法:

如果您自己编译了SetEnvX.exe,则可以设置该值,然后在cmd.exe中捕获它,而不是设置环境变量.例如:

If you compiled SetEnvX.exe by yourself, instead of setting up environment variable, you can print the value and then capture it in cmd.exe. E.g.:

for /f "delims=" %%k in ('SetEnvX.exe') do set VARIABLE=%%k

这篇关于可执行文件如何在父CMD或批处理上下文中设置环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆