批处理:如何添加 PATH 环境变量

Batch: How to Prepend the PATH Environment Variable

在 Windows 中,注册表项 HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\Path 包含 PATH 环境变量的内容。在我的例子中,PATH 环境变量是 REG_EXPAND_SZ 类型,内容为:

%SOME_PATH%\bin;C:\Windows

另外,我有一个名为PATH的用户环境变量,定义为:

%PATH%;C:\Users\Me\Bin

如果我在命令行输入ECHO %PATH%,输出是:

C:\Some\Path\bin;C:\Windows;C:\Users\Me\Bin

好的,现在根据上述情况获得所需的结果。我想从批处理脚本中永久添加机器的 PATH 变量。更改后,我希望所有新打开的命令 windows 无需注销或重新启动即可获取我的更改,并且上述注册表值应更改为:

C:\My\Path;%SOME_PATH%\bin;C:\Windows

在网上搜索如何执行此操作会产生以下方法:

1) SETX Path "C:\My\Path;%Path%" /m

   Result: C:\My\Path;C:\Some\Path\bin;C:\Windows;C:\Users\Me\Bin

   The first problem with this is that it expands the %SOME_PATH% environment
   variable to it's corresponding value.  The second is that %Path% expands
   to include the user's Path variable.

2) REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"^
       /v Path /t REG_EXPAND_SZ /d "C:\My\Path;%%B" /f

   Result: C:\My\Path;%SOME_PATH%\bin;C:\Windows

   The registry value ends up being correct, but I have to log off or
   restart to pick up the changes.

有没有办法在批处理文件中完成我想做的事情?

正如 @Harry Johnston 在他的评论中指出的那样,解决方案是在更改注册表值后对虚拟变量调用 SETX。在我的例子中,代码更改为:

REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"^
   /v Path /t REG_EXPAND_SZ /d "C:\My\Path;%%B" /f
SETX OS "%OS%" /M

我确认 WM_SETTINGCHANGE 消息不包含已更改的环境变量的名称,因此处理该消息的客户端(例如资源管理器)必须在收到消息时刷新所有环境变量。证明是消息只包含wParamlParam两个参数,在更改环境变量时设置如下:

wParam
When an application sends this message, this parameter must be NULL.

lParam
To effect a change in the environment variables for the system or the user, broadcast this message with lParam set to the string "Environment".