使用 WMI 设置环境变量不起作用,直到我们继续环境变量并按确定
这是上下文。我们使用我们的应用程序通过 WMI 设置许多内容,包括环境变量。
我们使用此代码(简化)来设置环境变量
ManagementClass envClass = new ManagementClass(this.oConnector.Scope, new ManagementPath(WMIHelper.Win32Environment), null);
ManagementObject mo = envClass.CreateInstance();
mo["Name"] = variable;
mo["UserName"] = user;
mo["VariableValue"] = value.Trim();
mo.Put();
现在,当我们打开命令提示符时,我们看不到环境变量的值。如果我打开计算机属性并进入环境变量页面,它就在那里。我按两次“确定”,重新打开命令提示符,变量突然就在那里。
有谁知道为什么会发生这种情况?就好像在放置环境变量后我们必须做其他事情来强制刷新或其他事情。
谢谢
Here is the context. We use our app to set many things by WMI, including environment variables.
We use this code (simplified) to set an environment Variable
ManagementClass envClass = new ManagementClass(this.oConnector.Scope, new ManagementPath(WMIHelper.Win32Environment), null);
ManagementObject mo = envClass.CreateInstance();
mo["Name"] = variable;
mo["UserName"] = user;
mo["VariableValue"] = value.Trim();
mo.Put();
Now when we open a command prompt we don't see the value of the environment variable. If I go and open computer properties and go into the Environment Variables page it's there. I press ok twice, reopen a command prompt and the variable all of a sudden is there.
Does anybody know why this is happening? It's almost as if after putting the environment variable we have to do something else to force a refresh or something.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您确定您在设置环境变量后启动读取环境变量的过程吗?
进程启动时会复制环境变量,进程启动后系统环境变量的任何更改都不会被进程看到。 AFAIK,没有办法绕过这种行为。通过打开一个新的 cmd 窗口,您将启动一个新的 cmd.exe 进程,该进程获取变量的新值。
Are you sure that you are starting the process that reads the environment variables after setting them?
Env vars are copied when a process starts, and any changes to the system's env vars after the process starts will never be seen by the process. AFAIK, there is no way to bypass that behavior. By opening a new cmd window, you are starting a new cmd.exe process, which gets the new values of the variables.