【发布时间】:2014-05-22 17:26:01
【问题描述】:
我已经阅读了很多关于这个主题的帖子并尝试了很多东西,但似乎无法让它发挥作用。我想设置一个环境变量,然后将该变量嵌套在 Path 环境变量中。我从批处理文件切换到 Powershell,因为我无法进行后期扩展以防止扩展路径中已经存在的嵌套变量等。
这是演示该问题的脚本。假设您已将 Maven 解压缩到 e:\Apps\maven\apache-maven-3.2.1 位置,测试脚本将运行,创建 MAVEN_HOME 变量,将该变量嵌套在 Path 中,并执行 mvn --help。
这一切都很好,除了打开一个新的命令提示符并输入ECHO %PATH% 很明显没有应用更改。
我听说环境变量的字母顺序可能很重要,但在这种情况下,“MAVEN_HOME”在“PATH”之前,所以这无关紧要。
Path 变量正在注册表中创建为REG_EXPAND_SZ 类型。
我正在从批处理文件运行 Powershell 脚本以避免签名:
Call Powershell.exe -executionpolicy bypass -File .\test.ps1
这是 Powershell 脚本:
#Environment Variable
$HOME_VAR = "MAVEN_HOME"
$HOME_PATH = "e:\Apps\maven\apache-maven-3.2.1"
$APP_CMD = "mvn"
$APP_ARGS = "--help"
#String to be added to the Path
$BIN_PATH = "%$HOME_VAR%\bin"
#Registry location of Machine Environment variables
$SYSVAR_REG_PATH = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
#Get the correct hive
$HKLM = [Microsoft.Win32.Registry]::LocalMachine
#Get the registry key with true to indicate that it is for editing
$sysvar_regkey = $HKLM.OpenSubKey($SYSVAR_REG_PATH, $TRUE)
#Set the value in the registry
$sysvar_regkey.SetValue($HOME_VAR, $HOME_PATH)
#Read the value back out
$HOME_PATH = $sysvar_regkey.GetValue($HOME_VAR)
#Set the value within the current process
[Environment]::SetEnvironmentVariable($HOME_VAR, $HOME_PATH, [EnvironmentVariableTarget]::Process)
#Must use RegistryKey to get value because it allows the "DoNotExpandEnvironmentNames" option
#This ensures that nested environment variables are not expanded when read
$envpath = $sysvar_regkey.GetValue("Path", "C:\Windows", [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
$segments = $envpath.split(";")
Write-Host "BEFORE"
Write-Host $env:path
#See if bin path is already in the Path
If (($segments -contains $BIN_PATH) -eq $FALSE) {
#Add the bin path to the path
$segments += $BIN_PATH
$envpath = $segments -join ";"
#RegistryValueKind.ExpandString ensures that variables in the path will expand when the Path is read
$sysvar_regkey.SetValue("Path", $envpath, [Microsoft.Win32.RegistryValueKind]::ExpandString)
}
#Read the path value as expanded
#All nested variables in the Path are expanded
$envpath = $sysvar_regkey.GetValue("Path")
#Update the Path for the current process
#Must do this every time to expand the Path
[Environment]::SetEnvironmentVariable("Path", $envpath, [EnvironmentVariableTarget]::Process)
Write-Host "AFTER"
Write-Host $env:path
#Run the command line
& $APP_CMD $APP_ARGS | Write-Host
【问题讨论】:
标签: windows batch-file powershell registry