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

84,062

Solution 1

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.

Solution 2

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.

Solution 3

As wizlb noted, doing

setx PATH "%cd%;%path%;" -m

will copy local env to system env, and without -m it will copy system env to user env. Neither is desirable. In order to accurately edit only one part of registry (system or user, system in my below example) you need to do this:

for /F "tokens=2* delims= " %%f IN ('reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path ^| findstr /i path') do set OLD_SYSTEM_PATH=%%g
setx.exe PATH "%OLD_SYSTEM_PATH%;%OTHER_STUFF%;" -m

Credit for the solution goes to http://www.robvanderwoude.com/ntregistry.php

Solution 4

To do this properly I think you really need to go beyond a simple batch file. The MSDN documentation states:

To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates.

First of all you won't be able to write to that key without a UAC elevation prompt. That's best arranged by adding the appropriate manifest to an executable file. Secondly, broadcasting WM_SETTINGCHANGE isn't simple from a batch file.

In your position I'd write a short and simple console app to do the job.

Solution 5

A simple (may be better) solution is to use PathMgr.cmd

Down the pathmgr_1.0.2.zip in https://gallery.technet.microsoft.com/Batch-Script-To-Manage-7d0ef21e

Unzip and put the pathmgr.cmd in the same folder as your batch file, then in your batch file write these two lines:

call pathmgr.cmd /del %cd% /y
call pathmgr.cmd /add %cd% /y

This will:

1) only update the user variable PATH, 2) will not include system PATH multiple times

You can also run the batch file multiple times, and it will only include your current path ONCE in the PATH.

Share:
84,062

Related videos on Youtube

KaiserJohaan
Author by

KaiserJohaan

Updated on October 22, 2020

Comments

  • KaiserJohaan
    KaiserJohaan over 3 years

    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.

    • Waihon Yew
      Waihon Yew almost 13 years
      If you change into that directory, won't your program pick them up? Maybe you can solve this by sidestepping the problem entirely?
    • David Heffernan
      David Heffernan almost 13 years
      @Jon isn't it dangerous to rely on working directory for DLL search? Best of all is to put DLLs in same directory as .exe and then there's no room for error.
    • Waihon Yew
      Waihon Yew almost 13 years
      @DavidHeffernan: I wouldn't say it's "dangerous". In any case, that decision has already been made by Microsoft and/or the program's author, so no changing that. Your answer is good (in fact I am your +1), but maybe this could be solved in 30 seconds instead?
  • Andriy M
    Andriy M almost 13 years
    @KaiserJohaan: Note also the absence of =, as the two commands look similar and the syntax might easily be confused.
  • KaiserJohaan
    KaiserJohaan almost 13 years
    I'm getting this in return: "ERROR: Invalid syntax. Default option is not allowed more tan 2 times" What does that imply?
  • Ryan Bemrose
    Ryan Bemrose almost 13 years
    Okay, can't link to the thread with the trailing backslash discussion (Why CAN'T posts contain that content, you stupid website?!). Do a search on "setx path spaces" to find the thread I was talking about.
  • Wayne Bloss
    Wayne Bloss over 12 years
    BE Careful if you do SETX PATH "%PATH%;C:\My\App" /M because the %PATH% variable expands to the user path + the system path, which could make the entire %PATH% greater than 1024 characters, which is the limit for expansion and it might duplicate some entries. A better way is to get the literal value from the PATH command and then set a literal value using SETX.
  • Jako
    Jako about 11 years
    Great answer! The others solutions will expand the variables to costants (SystemRoot, JAVA_HOME etc). Yours will preserve them
  • DenNukem
    DenNukem about 11 years
    One caveat is that you may have to reboot windows before changes take effect everywhere. I forgot where exactly it's a problem, so if you see anything weird just reboot and try again.
  • Dhawalk
    Dhawalk almost 11 years
    this is a better idea when your path will go over 1024 characters.
  • Millemila
    Millemila over 10 years
    Wizlb, thats a great point, but when I do set %PATH% or echo %PATH% I only see the system variables on my laptop. Are you sure of that?
  • n611x007
    n611x007 almost 10 years
    @wizlb good warn, it reads WARNING: The data being saved is truncated to 1024 characters. it screwed it up.
  • n611x007
    n611x007 almost 10 years
    you may be interested in the utility called SendMessage, to broadcast your WM_SETTINGCHANGE, from stefanstools sf net. source discussion wonders whether native vbscript would have some API wrappers lurking out there for this purpose.
  • JosefZ
    JosefZ over 9 years
    Get rid of ` delims= ` in your code. On my (retired) WinXP reg query delimites items by TABs, not with spaces! In typical output line we can identify (after four leading spaces): value name TAB value type TAB value
  • Genhis
    Genhis over 8 years
    I had to restart the computer to apply the changes.
  • Tyagi Akhilesh
    Tyagi Akhilesh about 8 years
    +1 for -m. One of my application (running an application as a service) required me to set system variable (not the user variable). Turns out, I was missing -m switch.
  • Reed Hedges
    Reed Hedges almost 8 years
    note that when you use %path% it will expand any variables that happen to be in %path%. I think you can maybe use setlocal EnableDelayedExpansion to prevent this.
  • Rahul Jawale
    Rahul Jawale about 6 years
    setx will set the variables for the user running the command. To set at the machine level use switch \M. Full command should look like setx \M http_proxy http://myproxyserver.com:80