Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persistently set a variable in Windows 7 from a batch file?

I am trying to set the PATH environment variable in windows 7 using a bat-file; however it does not seem to work.

I am using this windows command:

set PATH=%cd%;%path% pause 

However it only appears to be valid for this cmd instance. I want it to be permanent, since I first set the PATH and then run a program which needs to locate the libraries in that folder.

like image 740
KaiserJohaan Avatar asked Jun 29 '11 16:06

KaiserJohaan


People also ask

How do I permanently set an environment variable in PowerShell?

Using $env:Path variable in PowerShell to set environment variable for the session or temporary. Use [System. Environment] method in PowerShell to set environment variable permanently.

Can you use variables in batch files?

There are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command.


2 Answers

Use setx.exe instead of set.

setx PATH "%cd%;%path%;" pause 

Note that this sets the path for all future cmd instances, but not for the current one. If you need that, also run your original set command.

UPDATE: The second parameter needs to be quoted if it contains spaces (which %path% always has). Be warned that if the last character in your %path% is a backslash, it will escape the trailing quote and the last path entry will stop working. I get around that by appending a semicolon before the closing quote.

If you don't want to risk getting ";;;;;;" at the end of your path after repeated runs, then instead strip any trailing backslash from the %path% variable before setting, and it will work correctly.

like image 115
Ryan Bemrose Avatar answered Oct 10 '22 20:10

Ryan Bemrose


If you want to do it in a batch file, use the reg command to change the path value in the registry at the HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment key.

Something like:

reg add "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path /t REG_SZ /d "%path%;c:\newpath" 

Check that the path in the %path% variable matches the system path.

like image 42
simon Avatar answered Oct 10 '22 20:10

simon