luffy
luffy

Reputation: 2388

How can I refresh the PATH environment variable in a Batch script

I have a batch file "file.bat" that will call an installer with the following command:

msiexec.exe /i "%~dp0\installer.msi"

The installer will install a program and update the Path variable. While this works fine, the problem is when I try to start the program it's not found because apparently the PATH variable was not updated. I tried restarting the batch file from within itself with:

start cmd /c file.bat 

but it didn't work. Is there a way to refresh the PATH variable or maybe restart the batch file in a new process so that it detects the new environment?

PS: restarting the batch file manually works of course but it's not what I want.

Thanks.

Upvotes: 6

Views: 36019

Answers (4)

Arcy
Arcy

Reputation: 1

To reset the path within a Windows batch script, you can output the system environment variables from powershell and assign the output to the path as follows:

for /f "tokens=* usebackq" %%p in (powershell -Command "& {[System.Environment]::GetEnvironmentVariable('Path','Machine') + ';' + [System.Environment]::GetEnvironmentVariable('Path','User')}") do (set path=%%p)

Upvotes: 0

Arkadiusz Przechodzki
Arkadiusz Przechodzki

Reputation: 854

Easiest way, use Chocolatey (freeare). Then you will be able to reload PATH (with variable expansion) with a simple command:

refreshenv

Installation from cmd (requires admin rights):

@"%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"

Example usage:

> 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

Upvotes: 11

Jan de Nysschen
Jan de Nysschen

Reputation: 127

IN Windows PowerShell exit and run again

Upvotes: 3

J03L
J03L

Reputation: 324

simple batch file that refreshes the %path% environment variable:

@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%

Upvotes: 1

Related Questions