如何在批处理脚本中刷新 PATH 环境变量

luf*_*ffy 6 windows path batch-file environment-variables windows-server-2012

我有一个批处理文件“file.bat”,它将使用以下命令调用安装程序:

msiexec.exe /i "%~dp0\installer.msi"
Run Code Online (Sandbox Code Playgroud)

安装程序将安装程序并更新 Path 变量。虽然这工作正常,但问题是当我尝试启动程序时找不到它,因为显然 PATH 变量没有更新。我尝试从内部重新启动批处理文件:

start cmd /c file.bat 
Run Code Online (Sandbox Code Playgroud)

但它没有用。有没有办法刷新 PATH 变量或在新进程中重新启动批处理文件,以便检测新环境?

PS:手动重新启动批处理文件当然有效,但这不是我想要的。

谢谢。

Ark*_*zki 8

最简单的方法,使用 Chocolatey (freeare)。然后,您将能够使用简单的命令重新加载 PATH(带有变量扩展):

refreshenv
Run Code Online (Sandbox Code Playgroud)

从 cmd 安装(需要管理员权限):

@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
Run Code Online (Sandbox Code Playgroud)

用法示例:

> SET JAVA_HOME=c:/java/jdk6
> SET PATH=%JAVA_HOME%/bin
> ECHO %PATH%
c:/java/jdk6/bin

> SET JAVA_HOME=c:/java/jdk8
> refreshenv
Refreshing environment variables from registry for cmd.exe. Please wait...Finished..
> echo %PATH%
c:/java/jdk8/bin
Run Code Online (Sandbox Code Playgroud)


小智 1

刷新 %path% 环境变量的简单批处理文件:

@echo off
echo.
echo Refreshing PATH from registry

:: Get System PATH
for /f "tokens=3*" %%A in ('reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path') do set syspath=%%A%%B

:: Get User Path
for /f "tokens=3*" %%A in ('reg query "HKCU\Environment" /v Path') do set userpath=%%A%%B

:: Set Refreshed Path
set PATH=%userpath%;%syspath%

echo Refreshed PATH
echo %PATH%
Run Code Online (Sandbox Code Playgroud)