简体   繁体   English

通过 powershell 将环境变量设置为依赖于 windows 上的其他环境变量

[英]Setting environment variables as dependent on other env vars on windows via powershell

I want to set a variable say JAVA_HOME to dynamically assume the value of another variable say JAVA_HOME_x64..such that whenever JAVA_HOME_x64 changes and a new terminal session is created JAVA_HOME gets assigned the value of whatever is value of JAVA_HOME_x64.我想设置一个变量说 JAVA_HOME 来动态地假设另一个变量的值说 JAVA_HOME_x64 ..这样每当 JAVA_HOME_x64 更改并创建一个新终端 session 时,JAVA_HOME 就被分配了 JAVA_HOME_x64 的值。

In powershell, I do following...在 powershell 中,我执行以下操作...

[System.Environment]::SetEnvironmentVariable('JAVA_HOME', '%JAVA_HOME_x64%', 'Machine');
[System.Environment]::SetEnvironmentVariable('JAVA_HOME_x64', 'c:\myjava', 'Machine');
[System.Environment]::GetEnvironmentVariable('JAVA_HOME', 'Machine') ==> returns %JAVA_HOME_x64% 

When I open a new command prompt and type set(or echo %JAVA_HOME%), it shows me value of JAVA_HOME as %JAVA_HOME_x64% and not c:\myjava.当我打开一个新的命令提示符并键入 set(或 echo %JAVA_HOME%)时,它显示 JAVA_HOME 的值为 %JAVA_HOME_x64% 而不是 c:\myjava。

However if i go to UI(as below) and manually edit(delete and recreate) JAVA_HOME and reset its value to %JAVA_HOME_x64%, and then when a launch a new command prompt/terminal session it now shows value of JAVA_HOME as c:\myjava..Why so? However if i go to UI(as below) and manually edit(delete and recreate) JAVA_HOME and reset its value to %JAVA_HOME_x64%, and then when a launch a new command prompt/terminal session it now shows value of JAVA_HOME as c:\ myjava..为什么会这样? Any ideas?有任何想法吗? How to achieve the same behaviour as is in UI via PowerShell commands.如何通过 PowerShell 命令实现与 UI 中相同的行为。 通过 UI 手动设置环境变量

After some investigation i realize that, registry key(in Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment) created via above powershell command line for the said variable is of type REG_SZ, while the one created via UI is REG_EXPAND_SZ.经过一番调查,我意识到,通过上述 powershell 命令行为所述变量创建的注册表项(在 Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment 中)是 REG_SZ 类型,而通过 UI 创建的那个是 REG_EXPAND_SZ。 This maybe the clue这也许是线索

The following worked..以下工作..

Set-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' 'JAVA_HOME' '%JAVA_HOME_x64%' -Type 'ExpandString'

[System.Environment]::SetEnvironmentVariable('JAVA_HOME_x64','c:\program files\Zulu\jre','Machine')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM